Aovib Aovib - 1 month ago 11
JSON Question

How to parse JSON when the object contains an array of other objects?

I've been trying to parse a JSON in Swift where the object contains an array of other objects. Like this:

{
"people": [
{
"name": "Life Sciences",
"id": "4343435",

"children" : [
{
"name": "name1",
"id" : "5344444",
},

{
"name": "name2",
"id" : "5134343",
},
.....


I need to be able to access the name and id properties, but I can't seem to figure out what I'm doing wrong with my code below. My JSON file contains all the necessary data, yet, I keep getting the "unexpectedly found nil when unwrapping optional" error when I try to loop over the children array. Before that line the JSON is parsed correctly and works.

let loadURL = "https:// ....."
var people = [Person]()

func getPersonData() {
let request = URLRequest(url: URL(string: loadURL)!)
let urlSession = URLSession.shared
let task = urlSession.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
if let error = error {
print(error)
return
}
// Parse JSON data
if let data = data {
self.people = self.parseJsonData(data)
OperationQueue.main.addOperation{() -> Void in
self.tableView.reloadData()
}
}
})
task.resume()
}

func parseJsonData(_ data: Data) -> [Person] {
var people = [Person]()

do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary

// Parse JSON data
let jsonPeople = jsonResult?["people"] as! [AnyObject]
for jsonPerson in jsonPeople {
let person = Person()
person.name = jsonPerson["name"] as! String
person.id = jsonPerson["id"] as! String

//ERROR//: "unexpectedly found nil when unwrapping optional..."
let jsonChildren = jsonResult?["children"] as! [AnyObject]
for jsonChild in jsonChildren {
let child = Child()
child.name = jsonEntrance["name"] as! String
child.age = jsonEntrance["age"] as! Int

person.children.append(child)
}

people.append(person)
}
} catch {
print(error)
}
return people
}

Answer

You made an error here:

let jsonChildren = jsonResult?["children"] as! [AnyObject]

Should be:

let jsonChildren = jsonPerson["children"] as! [AnyObject]