我一直在尝试在 Swift 中解析 JSON,其中对象包含其他对象的数组。像这样:
{
"people": [
{
"name": "Life Sciences",
"id": "4343435",
"children" : [
{
"name": "name1",
"id" : "5344444",
},
{
"name": "name2",
"id" : "5134343",
},
.....
我需要能够访问 name 和 id 属性,但我似乎无法弄清楚我在下面的代码中做错了什么。我的 JSON 文件包含所有必要的数据,但是,当我尝试遍历子数组时,我不断收到“unexpectedly found nil when unwrapping optional”错误。在该行之前,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
}
最佳答案
你在这里犯了一个错误:
let jsonChildren = jsonResult?["children"] as! [AnyObject]
应该是:
let jsonChildren = jsonPerson["children"] as! [AnyObject]
关于ios - 当对象包含其他对象的数组时,如何解析 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40381544/