Your code cannot work. According to the given JSON the root object is an array [[String: Any]]
and there is no key result
at all.
let json = """
[{"id":1,"class":"A","Place":{"city":"sando","state":"CA"}},{"id":1,"class":"B","Place":{"city":"jambs","state":"KA"}}]
"""
let data = Data(json.utf8)
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] {
for item in json {
if let place = item["Place"] as? [String:String] {
print(place["city"]!, place["state"]!)
}
}
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString!)")
}
It’s much more convenient to use the Decodable
protocol to parse the JSON into structs
struct Response : Decodable {
private enum CodingKeys: String, CodingKey { case id, `class`, place = "Place" }
let id : Int
let `class` : String
let place : Place
}
struct Place : Decodable {
let city, state : String
}
...
do {
let result = try JSONDecoder().decode([Response].self, from: data)
for item in result {
print(item.place.city, item.place.state)
}
} catch { print(error) }
7
solved How to parse JSON values using Swift 4?