JSONDecoder - handle format mapping of capitalization like "object_id" to ObjectID?

I'm wondering if there's any good way to handle mapping of keys like e.g. object_id to a property named objectID. Other examples: siteURL and site_url.

There's the convertFromSnakeCase but that doesn't handle the last part of this (id to Id, url to Url only). Maybe it should, as it's IMHO a quite common case?

case convertFromSnakeCase

A key decoding strategy that converts snake-case keys to camel-case keys.

See the discussion in SR-6629 and the discussion of nuances in this area in PR#14039 [which unfortunately didn't land for Swift 5].

The right thing to do at the moment is to define a CodingKeys enum for your type with the appropriate string value.

2 Likes

Thank you for answering! :slightly_smiling_face:

It seems like there’s been an extensive discussion about this already, and I can only say that I agree with the conclusions that it’s quite a common case and a bit surprising.

Having this discussion after Swift 5 probably doesn’t make it any easier.

1 Like

Do you think there’s any chance that Norio Nomura’s PR might be reconsidered for Swift5.1?
Sincerely,
/morten

It's possible, yes, though not likely, unfortunately. The Swift 5.1 window is still open for overlay changes as far as I'm aware. My concerns about compatibility voiced in the PR have not changed, but if we go with @norio_nomura's PR, the new API would have to go through API review (since this is Foundation API, it would have to go through Foundation API review, not Swift Evolution, and I don't know if we have the bandwidth right now).

[I also forgot I had started a thread up about this a while back in Handling edge cases in JSONEncoder/JSONDecoder key conversion strategies (SR-6629)]

/CC @bendjones for visibility

3 Likes
Terms of Service

Privacy Policy

Cookie Policy