小编典典

Swift 4 JSON可编码ID作为键

swift

我想将Swift 4的可编码功能与json一起使用,但其中一些键没有设置名称。而是有一个数组,它们是像

{
 "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,以便我将其指定为密钥吗?该数字可以是任何数字,并且每个数字都不相同。

想要这样的事情

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
}

提前致谢。


阅读 332

收藏
2020-07-07

共1个答案

小编典典

请检查 :

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)")
}
2020-07-07