使用ObjectMapper iOS有效解析JSON数据

时间:2018-09-17 19:02:59

标签: ios json swift objectmapper

嗨,我有一个JSON,格式为给定

"exclusions": [
    [
      {
        "facility_id": "1",
        "options_id": "4"
      },
      {
        "facility_id": "2",
        "options_id": "6"
      }
    ],
    [
      {
        "facility_id": "1",
        "options_id": "3"
      },
      {
        "facility_id": "3",
        "options_id": "12"
      }
    ],
    [
      {
        "facility_id": "2",
        "options_id": "7"
      },
      {
        "facility_id": "3",
        "options_id": "12"
      }
    ]
  ]

我正在使用Object Mapper库来解析JSON,但是据我所知,我感觉它缺少一个键,因为键exclusions下的每个对象都是一个数组, 无论如何,我可以使用ObjectMapper对此进行解析

1 个答案:

答案 0 :(得分:1)

为什么不Codable

class Root:Codable {
  let exclusions:[[InnerItem]]
}
class InnerItem:Codable {
   let facilityId:String
   let optionsId:String
  private enum CodingKeys: String, CodingKey {
     case facilityId = "facility_id"
     case optionsId = "options_id"
  }
}

//

do {
     let decoded = try JSONDecoder().decode(Root.self, from:jsonData)
     print(decoded)
} catch {
    print(error)
}

顺便说一句,您的json需要一个环绕的{}