json - Swift 4 JSON Codable id 作为键

标签 json swift codable

我想使用 Swift 4 的 json 编码功能,但某些键没有设置名称。相反,有一个数组,它们是类似 id 的

{
 "status": "ok",
 "messages": {
   "generalMessages": [],
   "recordMessages": []
 },
 "foundRows": 2515989,
 "data": {
   "181": {
     "animalID": "181",
     "animalName": "Sophie",
     "animalBreed": "Domestic Short Hair / Domestic Short Hair / Mixed (short coat)",
     "animalGeneralAge": "Adult",
     "animalSex": "Female",
     "animalPrimaryBreed": "Domestic Short Hair",
     "animalUpdatedDate": "6/26/2015 2:00 PM",
     "animalOrgID": "12",
     "animalLocationDistance": ""

您可以在其中看到 181 个 id。有谁知道如何处理 181,以便我可以将其指定为 key ?该数字可以是任意数字,并且每个数字都不同。

想要这样的东西

struct messages: Codable {
    var generalMessages: [String]
    var recordMessages: [String]
}

struct data: Codable {
    var
}

struct Cat: Codable {
    var Status: String
    var messages: messages
    var foundRows: Int
    //var 181: [data] //What do I place here
}

提前致谢。

最佳答案

请检查:

struct ResponseData: Codable {
    struct Inner : Codable {
        var animalID   : String
        var animalName : String

        private enum CodingKeys : String, CodingKey {
            case animalID     = "animalID"
            case animalName   = "animalName"
        }
    }

    var Status: String
    var foundRows: Int
    var data : [String: Inner]

    private enum CodingKeys: String, CodingKey {
        case Status = "status"
        case foundRows = "foundRows"
        case data = "data"
    }
}

let json = """
    {
        "status": "ok",
        "messages": {
            "generalMessages": ["dsfsdf"],
            "recordMessages": ["sdfsdf"]
        },
        "foundRows": 2515989,
        "data": {
            "181": {
                "animalID": "181",
                "animalName": "Sophie"
            },
            "182": {
                "animalID": "182",
                "animalName": "Sophie"
            }
        }
    }
"""
let data = json.data(using: .utf8)!
let decoder = JSONDecoder()

do {
    let jsonData = try decoder.decode(ResponseData.self, from: data)
    for (key, value) in jsonData.data {
        print(key)
        print(value.animalID)
        print(value.animalName)
    }
}
catch {
    print("error:\(error)")
}

关于json - Swift 4 JSON Codable id 作为键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57242990/

相关文章:

java - JSON 文件未复制到目标文件夹

javascript - 当“下拉菜单值更改”时重新加载 d3 图表

arrays - 动画数组结束于第一张图片

json - 如何使用带有嵌套 JSON 结构和未知键的 Swift Codable

swift - 如何实现上下文可控的 Swift Codable Encode 函数?

java - 在groovy中解析JSON时如何保持键的顺序

java - 将 json 部分反序列化为 POJO,但保留一些原始 json 作为字段

ios - 在选择/取消选择 UIButton 之间切换

swift - 为什么 Swift 1.2 破坏了 UIDynamicAnimator 的 init(collectionViewLayout :)?

ios - Swift 4 可解码 : The given data was not valid JSON