I am having a bear of a time understanding simple JSON serialization principles with Swift 3. Can I please get some help with decoding JSON from a website into an array so I can access it as jsonResult["team1"]["a"]
etc? Here is relevant code:
let httprequest = URLSession.shared.dataTask(with: myurl){ (data, response, error) in
self.label.text = "RESULT"
if error != nil {
print(error)
} else {
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options:
JSONSerialization.ReadingOptions.mutableContainers)
print(jsonResult) //this part works fine
print(jsonResult["team1"])
} catch {
print("JSON Processing Failed")
}
}
}
}
httprequest.resume()
the incoming JSON is:
{
team1 = {
a = 1;
b = 2;
c = red;
};
team2 = {
a = 1;
b = 2;
c = yellow;
};
team3 = {
a = 1;
b = 2;
c = green;
};
}
Thanks
An object that converts between JSON and the equivalent Foundation objects.
Reading OptionsSpecifies that leaf strings in the JSON object graph are mutable. Specifies that the parser allows top-level objects that aren't arrays or dictionaries. Specifies that reading serialized JSON data supports the JSON5 syntax.
Specifies that arrays and dictionaries in the returned object are mutable.
In Swift 3, the return type of JSONSerialization.jsonObject(with:options:)
has become Any
.
(You can check it in the Quick Help pane of your Xcode, with pointing on jsonResult
.)
And you cannot call any methods or subscripts for the variable typed as Any
. You need explicit type conversion to work with Any
.
if let jsonResult = jsonResult as? [String: Any] {
print(jsonResult["team1"])
}
And the default Element type of NSArray
, the default Value type of NSDictionary
have also become Any
. (All these things are simply called as "id-as-Any", SE-0116.)
So, if you want go deeper into you JSON structure, you may need some other explicit type conversion.
if let team1 = jsonResult["team1"] as? [String: Any] {
print(team1["a"])
print(team1["b"])
print(team1["c"])
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With