使用JSONSerialization.jsonObject反序列化swift 5中的JSON
我正在尝试在swift中反序列化json对象。JSON如下所示:使用JSONSerialization.jsonObject反序列化swift 5中的JSON,json,macos,serialization,Json,Macos,Serialization,我正在尝试在swift中反序列化json对象。JSON如下所示: let data = """ { "code": 200, "message": "OK", "results": [ { "id": 111, "name": "Tony"}, { "id": 112, "name": "Bill"}, { "id": 112, "name": "John"} ] } """.data(using: .utf8)!
let data = """
{
"code": 200,
"message": "OK",
"results": [
{ "id": 111, "name": "Tony"},
{ "id": 112, "name": "Bill"},
{ "id": 112, "name": "John"}
]
}
""".data(using: .utf8)!
我用它来反序列化JSON
var json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
print (json!["code"]!)
print (json!["message"]!)
print (json!["results"]!)
在每种情况下都会打印正确的值,但我不知道如何遍历
json!["reults"]
错误消息是:
Type 'Any' does not conform to protocol 'Sequence'
在第一个答案之后添加
第一个答案解决了这个问题。然而,我在Apple devoper的网站上发布了以下代码,它们可以做到这一点:
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
for case let result in json["results"] {
if let restaurant = Restaurant(json: result) {
restaurants.append(restaurant)
}
}
它们传入的结果是一个字符串,这只是一个老例子吗?我可以沿着这条路径继续吗?您必须将结果的值向下转换到字典{}的数组[]。然后迭代数组
let results = json!["results"] as! [[String:Any]]
for item in results {
print(item["name"] as! String, item["id"] as! Int)
}
旁注:在Swift 4+中,可编码协议是更好的选择
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] ?? [:]
if let dictJson = json { //If json is not nil
if let arrResults = dictJson["results"] as? Array<Dictionary<String,Any>>{ //If results is not nil
for result in arrResults {
print(result) //Prints result
}
}
}
试试这个。它将迭代结果