I am trying to json parsing in swift 3. I am getting the above mentioned error. My parsing technique is as follows:
if let responseData = data {
do {
let json = try JSONSerialization.jsonObject(with: responseData, options: JSONSerialization.ReadingOptions.allowFragments)
if let dict = json as? [Dictionary<String, AnyObject>] {
if let localityName = dict["name"] as? String ,let localityId = dict["_id"] as? String {
}
}
} catch {
print("could not serialize")
}
}
I am getting the error in the line:
if let localityName = dict["name"] as? String ,let localityId = dict["_id"] as? String
please let me know how can I fix this issue
The dict
property is an array of dictionaries, not a dictionary. You could access the first elements name the following:
dict.first?["name"]
dict
is actually arr
. Create a loop to iterate thru it
if let arr = json as? [Dictionary<String, AnyObject>] {
for item in arr {
if let localityName = item["name"] as? String,
let localityId = item["_id"] as? String {
print(localityName, localityId)
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.