2016-11-02 66 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不是根對象的關鍵。