一、使用自带的JSONSerialization</big>
苹果从IOS5.0后推出了SDK自带的JSON解决方案NSJSONSerialization。而自Swift3起,这个又改名成JSONSerialization。这是一个非常好用的JSON生成和解析工具,效率也比其他第三方开源项目高。
JSONSerialization能将JSON转换成Foundation对象,也能将Foundation对象转换成JSON,但转换成JSON的对象必须具有如下属性:
1、顶层对象必须是Array或者Dictionary
2、所有的对象必须是String、Number、Array、Dictionary、Null的实例
3、所有Dictionary的key必须是String类型
4、数字对象不能是非数值或无穷
注意:尽量使用JSONSerialization.isValidJSONObject先判断能否转换成功。
将对象转成json字符串,再转回来
func testJSON()
{
//Swift对象
let user:[String: Any] = [
"uname": "张三",
"tel": ["mobile": "138", "home": "010"]
]
if !JSONSerialization.isValidJSONObject(user) {
print("数据结构错误")
return
}
// 利用自带的json转换成data
//如果设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读
let data = try? JSONSerialization.data(withJSONObject: user, options: [])
//Data转换成String打印输出
let dataString = String(data: data!, encoding: String.Encoding.utf8)
//输出json字符串
print("Json Str:\(dataString ?? "")");
//把Data对象转换回JSON对象
let json = try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? [String:Any]
print("Json Object:", json ?? [:])
let uname = json?["uname"]
let mobile = (json?["tel"] as! [String: Any])["mobile"]
print("get Json Object:","uname: \(uname ?? ""), mobile: \(mobile ?? "")")
}
输出结果如下:
Json Str:{"uname":"张三","tel":{"home":"010","mobile":"138"}}
Json Object: ["uname": 张三, "tel": {
home = 010;
mobile = 138;
}]
get Json Object: uname: 张三, mobile: 138
解析json字符串
(由于是字符串内容是json数组,则转成NSArray。如果字符串是json对象,则转成NSDictionary。)
func JSONString()
{
let string = "[{\"ID\":1,\"Name\":\"元台禅寺\",\"LineID\":1},{\"ID\":2,\"Name\":\"田坞里山塘\",\"LineID\":1},{\"ID\":3,\"Name\":\"滴水石\",\"LineID\":1}]"
let data = string.data(using: String.Encoding.utf8)
let jsonArr = try! JSONSerialization.jsonObject(with: data!,
options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String: Any]]
print("记录数:\(jsonArr.count)")
for json in jsonArr {
print("ID:", json["ID"]!, " Name:", json["Name"]!)
}
}
输出结果:
记录数:3
ID: 1 Name: 元台禅寺
ID: 2 Name: 田坞里山塘
ID: 3 Name: 滴水石
原文出自:www.hangge.com 转载请保留原文链接:https://www.hangge.com/blog/cache/detail_647.html