我一直試圖解析一個JSON在Swift中的對象包含其他對象的數組。就像這樣:如何在對象包含其他對象數組時解析JSON?
{
"people": [
{
"name": "Life Sciences",
"id": "4343435",
"children" : [
{
"name": "name1",
"id" : "5344444",
},
{
"name": "name2",
"id" : "5134343",
},
.....
我需要能夠訪問的名稱和ID屬性,但我似乎無法找出我在做什麼毛病我下面的代碼。我的JSON文件包含了所有必要的數據,但是當我試圖循環訪問子數組時,我一直在獲取「意外地發現爲零」,當展開可選的「」錯誤時。在該行之前,JSON被正確解析並運行。
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
}