How to decode JSON with integer as key in Swift 4?

enter image description here

As you can see, the right hand data has keys like "7", "8" etc... Now I know that these are not quite "integers" because they are numbers in String. However, when I decode them, I need to use that key name as the variable name. But, we cannot have number as a variable name.

What should I do in this case? How can I decode this?

Is it just better to re-create the dataset so that it does not have the number as the key? But then, what do people do when they do not have control the dataset?

The entire code is too long and irrelevant so I just took a screenshot. If you want, you can see the JSON data here https://api.myjson.com/bins/11r19i

1 answer

  • answered 2018-11-08 07:20 Tobi

    You can use CodingKey to achieve that.

    struct bus: Codable {
        var one: String?
        var two: String?
        var three: String?
        enum CodingKeys: String, CodingKey {
            case one  = "1"
            case two = "2"
            case three = "3"
        }
    }
    

    it will decode those keys inside each case, you should be able to recognize now.