I tried to parse a JSON file and when I parse it as per the syntax, it gives me an error that cannot change the string to an array of dictionary, but when I fix the problem, it generates nil
. Can anyone give an opinion?
func jsonFour() {
let string = "[{\"address\": 7023000630,\"reportStatus\": \"Retrieved\",\"currentLocation\": {\"latitude\": 29.8529, \"longitude\": 73.99332,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\"} }, {\"address\": 7290098339, \"reportStatus\": \"Retrieved\", \"currentLocation\": {\"latitude\": 21.628569, \"longitude\": 72.996956,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\" } } ]"
let data = string.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : JSONSerialization.ReadingOptions.mutableContainers) as? [[ String : Any ]]
{
print(jsonArray) // use the json here
let address = jsonArray["address"] as! [[String:Any]]
if let timestamp = address["timestamp"] as? [String]{print(timestamp)}
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
}
When I remove the double brackets from "String : Any"
, it runs fine, but does not give any value but nil
.
And when I proceed with this way, it skips the if statement and just prints:
"bad json".
What am I doing wrong here?
In your code snippet jsonArray
is an array
and array can't subscript a value of type [[String: Any]]
, so instead you should parse like,
func jsonFour(){
let string = "[{\"address\": 7023000630,\"reportStatus\": \"Retrieved\",\"currentLocation\": {\"latitude\": 29.8529, \"longitude\": 73.99332,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\"} }, {\"address\": 7290098339, \"reportStatus\": \"Retrieved\", \"currentLocation\": {\"latitude\": 21.628569, \"longitude\": 72.996956,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\" }}]"
let data = string.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : JSONSerialization.ReadingOptions.mutableContainers) as? [[String: Any]]
{
print(jsonArray) // print the json here
for jsonObj in jsonArray {
if let dict = jsonObj as? [String: Any] {
if let address = dict["address"] {
print(address)
}
if let location = dict["currentLocation"] as? [String: Any], let timeStamp = location["timestamp"] {
print(timeStamp)
}
}
}
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
}