Gregory Williams Gregory Williams - 24 days ago 6
JSON Question

Swift 4 JSON Codable ids as keys

I would like to use Swift 4's codable feature with json but some of the keys do not have a set name. Rather there is an array and they are ids like

{
"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": ""


where you see the 181 ids. Does anyone know how to handle the 181 so I can specify it as a key? The number can be any number and is different for each one.

Would like something like this

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
}


Thanks in advance.

Answer Source

Please check :

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