Answer the question
In order to leave comments, you need to log in
How to parse such json in swift?
Plz tell me how to parse this json?
I can't figure out how to get the elements of an array
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! Dictionary<String, Any>
let fixtures = json["fixtures"]
for fixture: (String, Any) in fixtures {
print(fixture)
}
Answer the question
In order to leave comments, you need to log in
I would still advise parsing in the model, because such a method as yours is bad. Plus there are a bunch of different libraries for parsing.
let fixtures = json["fixtures"] as!
What if an [int: int] array comes from the server, then your application will crash. Better not use force unwrap
struct Fixtures {
var links: Links
.....
var result: Result
}
struct Links {
...
}
struct Result {
...
}
immediately parsed into the model and take anything from there
I use the SwiftyJSON library
let task = session.dataTask(with: request) { (data, response, error) -> Void in
if error == nil {
let swiftyJSON = try! JSON(data: data!)
let fixtures = swiftyJSON["fixtures"].arrayValue
for element in fixtures {
let data = element["data"].stringValue
print(data) -> "2018"
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question