let jsonbody : [String : Any] = [
"name" : "jiajia",
"age" : 18
]
//json 的可用性判断
if !JSONSerialization.isValidJSONObject(jsonbody) {
print("不能转化")
return
}
//json 字符串转换为data
guard let data = try? JSONSerialization.data(withJSONObject: jsonbody, options: .prettyPrinted) else { return }
//data 转为字符串
let jsonstr = String(data: data, encoding: .utf8)
print("Json Str" + jsonstr!)
//.allowFragment 允许json字符串最外层不是array 或 dictionary 但必须是有效的json格式
//.mutableContainers 返回可变容器 array 或 dictionary
if let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String : Any] {
print("jsonDic:",json)
let name = json["name"]
let age = json["age"]
print("name:\(name),age:\(age)")
}
网友评论