1

I am trying to use Codable to automatically parse incoming JSON into my models. It is working fine, but then I learnt about _keyDecodingStrategy_, and wanted to use this. It is working great and able to lessen my code as I do not have to write CodingKeys enum for my models.

But now the problem is a new variable sent from server. The variable is post_url_110x110.

I thought it will convert to postUrl110x110, but it doesn't. Do help me into its camelCase conversion or suggest if I should avoid automatic conversion in this case.

Kaushik Makwana
  • 1,329
  • 2
  • 14
  • 24
Amit Gupta
  • 192
  • 2
  • 13
  • 1
    You should update your question to include the actual JSON that you need to decode along with your data model and the code you use for decoding. – Dávid Pásztor Jan 03 '19 at 10:20
  • `.keyDecodingStrategy` and `CodingKeys` can be used side by side at a time. And you have to use both of them. The downside is you have to cover all the cases for `CodingKeys`. Just provide the raw values of those properties which fail when `.convertFromSnakeCase` is applied. Leave other cases (meaning, you don't have to write the raw values). To know more see [this answer](https://stackoverflow.com/a/49888925/3687801) – nayem Jan 03 '19 at 10:51
  • Yes. KeyDecodingStrategy is an improvisation on my existing json decoding using Codable. – Amit Gupta Jan 03 '19 at 11:00

2 Answers2

2

It will work for you if you rename your data model property from postUrl110x110 to postUrl110X110 with capital X. I know it's not ideal solution but it's worth noting. Check the example below:

struct DataItem: Codable {
    var itemId: String
    var postUrl110X110: String
}

let json = """
{
    "item_id": "abcd",
    "post_url_110x110": "https://example.org/image.png"
}
""".data(using: .utf8)!

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase

print(try! decoder.decode(DataItem.self, from: json))
Martin Pilch
  • 3,245
  • 3
  • 38
  • 61
  • Wonderful Martin. Thanks a lot. This was what I exactly wanted. I could change my model name, but had no control on the incoming json. Now I am able to seamlessly parse json directly to my model using Codable + keyDecodingStrategy. Thanks again. – Amit Gupta Jan 03 '19 at 11:20
0

You can try this tool.

Sample input

enter image description here

Output

enter image description here

  • If you need further assistance then let me know.
dahiya_boy
  • 9,298
  • 1
  • 30
  • 51
  • From my point of view this answer is not valid. Amit is asking for the way using keyDecodingStrategy without writing CodingKeys manually – Martin Pilch Jan 03 '19 at 10:49