Reputation: 1826
I am trying to get Attendance Value from this json file "321" , the Date "654" and the value "123" from the "Number" in "@attributes". I have manage to filter through the levels but I was wondering if there is a more efficient way of accessing values in levels greater than three. Or is there a library similar to linq in csharp.
Can I just jump to "GameData" and get all the GameData and store to a list of objects.
or just a chain e.g:
json["level1"].["level2"].["level3"]
Json:
{
"Feed":{
"Doc":{
"Comp": {
},
"GameData": {
"GameInfo": {
"Attendance": 321,
"Date": 654,
"ID": 00
}
},
"GameData": {
"GameInfo": {
"Attendance": 321,
"Date": 654
"ID": 01
}
}
},
"@attributes": {
"Number": 123
}
}
}
Code:
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String: AnyObject]
if let articlesFromJson = json["Feed"] as? [String: AnyObject]{
print("level1")
if let aFromJson = articlesFromJson["Doc"] as? [String: AnyObject]{
print("level2")
if let aFromJson = articlesFromJson["GameData"] as? [String: AnyObject]{
print(aFromJson)
}
}
}
Upvotes: 1
Views: 893
Reputation: 10433
I really like SwiftyJson that lets you do:
import SwiftyJSON
let json = JSON(data: data)
let game = json["Feed"]["Doc"]["GameData"] // this is of type JSON
let attendance = game["GameInfo"]["Attendance"].string ...
let number = json["Feed"]["@attributes"]["Number"].string // this is of type String?
let number = json["Feed"]["@attributes"]["Number"].stringValue // this is of type String, and will crash if the value is missing
=== EDIT: info on duplicated tags ===
JSON itself doesn't prevent you from doing so: https://stackoverflow.com/a/21833017/2054629 but you'll find that most librairies understand JSON as dictionaries and arrays, and those structures can't have duplicated keys.
For instance in javascript that you can test in your browser console:
JSON.stringify(JSON.parse('{"a": 1, "a": 2}')) === '{"a": 2}'
and I believe SwiftyJson behave similarly. SO I'd suggest you change your JSON structure to:
{
"Feed":{
"Doc":{
"Comp": {},
"GameData": {
"GamesInfo": [
{
"Attendance": 321,
"Date": 654,
"ID": 0
},
{
"Attendance": 321,
"Date": 654
"ID": 1
}
]
},
},
"@attributes": {
"Number": 123
}
}
}
Upvotes: 1
Reputation: 197
Loop through the arrays until you are at the loop of the object you need. Then cast that value as needed.
Upvotes: 0