// 字典转json
var dict = ["男":"杰克","女":"萝丝"]
if (JSONSerialization.isValidJSONObject(dict)){
let jsonData:NSData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) as NSData
let json:String = (NSString(data:jsonData as Data, encoding:String.Encoding.utf8.rawValue))! as String
print(json)
// json转字典
let dict1 = try JSONSerialization.jsonObject(with:jsonData as Data, options: .mutableContainers) as! NSDictionary
print(dict1)
let value02 = dict1["男"]!;
print(value02)
}
输出为:
{
"男" : "杰克",
"女" : "萝丝"
}
{
"\U5973" = "\U841d\U4e1d";
"\U7537" = "\U6770\U514b";
}
杰克