簡體   English   中英

當對象包含其他對象數組時,如何解析JSON?

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

我一直在嘗試在Swift中解析JSON,其中該對象包含其他對象的數組。 像這樣:

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

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

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

我需要能夠訪問name和id屬性,但是似乎無法弄清楚下面的代碼在做什么。 我的JSON文件包含所有必要的數據,但是,當我嘗試遍歷children數組時,我不斷收到“在打開可選包裝時意外發現nil”錯誤。 在該行之前,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]

可能您的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數據處理。

您的代碼看起來不錯,但是問題是您正在搜索錯誤的字典。 您的“ jsonResult”鍵沒有“兒童”鍵。 但是您的“ jsonPerson”對象具有“子級”鍵。 替換下面的代碼行-

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

將此行替換為此-

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

首先,JSON不代表代碼中的實際JSON。

其次,除非別無選擇,否則永遠不要在Swift中使用NSDictionary

第三,將包含字典的JSON數組強制轉換為[[String:Any]] ,從不強制轉換為[Any(Object)]

第四,Swift 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在代碼孩子回路不存在, children是一個重要people不是的根對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM