Reputation: 511
I'm trying to deserialize a json object in swift. The JSON looks like this:
let data = """
{
"code": 200,
"message": "OK",
"results": [
{ "id": 111, "name": "Tony"},
{ "id": 112, "name": "Bill"},
{ "id": 112, "name": "John"}
]
}
""".data(using: .utf8)!
I'm using this to deserialize the JSON
var json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
print (json!["code"]!)
print (json!["message"]!)
print (json!["results"]!)
The correct values are printed in each case, but I can not figure out how to iterate across the value returned by
json!["reults"]
The error message is:
Type 'Any' does not conform to protocol 'Sequence'
Added- after first answer
First answer solves this problem. However, I'm following code from Apple Deveoper's site they do this:
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)
}
}
And the result they pass in is a String, is this just an old example? Can I continue down this path?
Upvotes: 0
Views: 4095
Reputation: 46
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
}
}
}
Try this. It will iterate result.
Upvotes: 1
Reputation: 285270
You have to downcast the value of results
to an array ([]
) of dictionaries ({}
). Then iterate the array
let results = json!["results"] as! [[String:Any]]
for item in results {
print(item["name"] as! String, item["id"] as! Int)
}
Side note: In Swift 4+ the Codable
protocol is the better choice
Upvotes: 1