2016-11-02 64 views
0

我一直试图解析一个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 
} 

回答

1

您在这里犯了一个错误:

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

应该是:

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

可能是,您的JSON数据在某些点上没有“子”值,请尽量避免强制转换为[AnyObject]。您可以尝试去改变它以这样的方式

if let result = jsonResult, let jsonChildren = result["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) 
     } 
} 

此外,您可以尝试使用SwiftyJSON这将帮助你更容易做你的JSON数据处理。

0

您的代码看起来不错,但问题是,你是寻找错误的字典。你的'jsonResult'键没有'孩子'的键。但是你的'jsonPerson'对象有一个'children'键。更换你的下面的代码行 -

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

与这一个替换该行 -

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

0

首先,将JSON并不代表代码中实际的JSON。

其次,永远不会在Swift中使用NSDictionary除非你别无选择。

所有的第三,铸造含有字典的JSON阵列[[String:Any]],从不[Any(Object)]

第四所有的,在夫特3 JSON字典是[String:Any]

所有的五,使用可选的绑定,以避免运行时错误(崩溃)

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

    do { 
    let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:Any] 

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

     // children is a key of a person not of the root object ! 
     if let jsonChildren = jsonPerson["children"] as? [[String:Any]] { 
      for jsonChild in jsonChildren { 
      let child = Child() 
      child.name = jsonChild["name"] as! String 
      child.age = jsonChild["age"] as! Int 

      person.children.append(child) 
      } 
     } 

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

PS:你会得到另一个错误未定义的标识符因为jsonEntrance代码中的子循环中不存在,childrenpeople不是根对象的关键。