2

I've set up a Decodable struct for a nested JSON that I'm receiving.

One of the keys starts with a number, and I understand that with Decodable the vars in the struct should have the same name as the key in the JSON structure so that it decodes automatically.

The key is "7d", and the value is an array of structures, like this:

"7d":[
      {
       "itemid":7,
       "categoryid":1,
       "name":"item"
      },
      {
       ...
      }
     ],
"cvn":[{...},{...}],
...

Following the accepted answer to the question How to decode a nested JSON struct with Swift Decodable protocol?, I have a struct of item in my RawDecodableStruct like this:

struct item: Decodable {
    var itemid: Int
    var category_id: Int
    var name: String
}

And then I have this:

struct categories: Decodable {
    var 7d: [item]
    var cvn: [item]
    ...
}

For the line with 7d, I get this error:

'd' is not a valid digit in integer literal

So how can I deal with this problem?

I do have access to the system that is producing the JSON data, so I could change the key to something that doesn't start with a number, but another client is already working on that system so it would take some work to adapt everything. Is there some easy solution in Swift or is it easier to just change the key?

Gimme the 411
  • 994
  • 9
  • 25
  • 1
    Use a more "readable name" without the number of name it sevenD if you really want to keep it, and use CodingKeys: https://stackoverflow.com/questions/44396500/how-do-i-use-custom-keys-with-swift-4s-decodable-protocol – Larme Jul 08 '18 at 13:37
  • 1
    this problem is because swift doesn't allow you have variable names starting with a digit – S1LENT WARRIOR Jul 08 '18 at 13:38

0 Answers0