基本对象和JSON之间的转化

OC实现

- (id)objectFromJsonString:(NSString *)jsonString {
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
    return jsonObject;
}

- (NSString *)jsonStringFromObject:(id)jsonObject { // 一般为Map
    if ([NSJSONSerialization isValidJSONObject:jsonObject]) {
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:0 error:&error];
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        return json;
    }
    return nil;
}

Swift实现

import Foundation

func objectFromJsonString(jsonString: String) -> Any? {
    if let jsonData = jsonString.data(using: .utf8) {
        do {
            let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)
            return jsonObject
        } catch {
            print("Error parsing JSON: \(error)")
            return nil
        }
    }
    return nil
}

func jsonStringFromObject(jsonObject: Any) -> String? {
    if JSONSerialization.isValidJSONObject(jsonObject) {
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: [])
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                return jsonString
            }
        } catch {
            print("Error creating JSON: \(error)")
            return nil
        }
    }
    return nil
}

你可能感兴趣的:(基本对象和JSON之间的转化)