当父母和孩子的数据相同时,如何使用Alamofire解析数据?

时间:2018-11-07 15:26:53

标签: ios swift alamofire swifty-json

我正在使用Alamofire来调用和解析json数据,但问题是响应不正确。父级和子级具有相同的数据,因此解析器更改了解析中的ID,并减少了项数。下面的数据是我想使用模型解析的json

{
"error": false,
"message": "",
"data": [
    {
        "id": 1,
        "parent_id": null,
        "name": "Ink Cartridge",
        "notes": null,
        "children": [
            {
                "id": 5,
                "parent_id": 1,
                "name": "Colored",
                "notes": null
            }
        ]
    },
    {
        "id": 2,
        "parent_id": null,
        "name": "Toner Cartridge",
        "notes": null,
        "children": []
    },
    {
        "id": 3,
        "parent_id": null,
        "name": "Combo",
        "notes": null,
        "children": []
    },
    {
        "id": 4,
        "parent_id": null,
        "name": "Combo Set",
        "notes": null,
        "children": []
    }
]

}

我正在使用Alamofire和SwiftyJSON库

Alamofire.request(ServerAPI.getCategories()).responseJSON { (responseData) -> Void in
        if((responseData.result.value) != nil) {
            let swiftyJsonVar = JSON(responseData.result.value!)
            print(swiftyJsonVar)
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试一下,您应该使用Codable,因为它使此操作变得容易得多。 构建这些结构后,父结构将使用常量名称遍历数据,因此,例如让id为例,您将获得数据的“ id”部分。然后,我构建了另一个结构,以便当它遍历子级时,将使用该结构在内部执行相同的操作。

  struct Parent: Codable {

   let id: Int
   let parent_id: Int?
   let name: String
   let notes: String?
   let children: [Child]?

  }

  struct Child: Codable {

      let id: Int
      let parent_id: Int?
      let name: String
      let notes: String?
  }

然后您需要一个变量来保存此数据:

 var completeData = [Parent]()

并在您的通话中:

      do {
let dataParsed = try JSONDecoder().decode([Parent].self, from: data
 self.completeData = dataParsed

} catch {
print(error)
}

并访问它,您应该能够

var accessingID = self.completeData[0].id

并为孩子:

var accessingChild = self.completeData[0].children.id

我不确定您要如何获取数据,因此您可能想弄乱数组的处理方式,虽然我无法进行测试,但是应该遵循这些原则。

请记住,如果该值可能为null,则需要使用?。该方法也没有使用Alamofire或SwiftyJSON,因为Codable使使用结构进行此类操作更加快捷方便。