Friday, October 6, 2017

When JSONDecoder Meets the Real World

Dave Lyon:

Take for example the “empty” object in JSON. You might expect that an object nested under another object would either be a complete and valid object or would be null – and this is what JSONDecoder expects as well. But in many cases an API might return an empty object (that looks like {}) and cause your JSON decoding to fail even if you’re decoding in to an Optional.

When faced with this issue recently I came up with a protocol based solution to work around this issue. I also made sure that the behavior was “opt-in” so that its possible to be flexible if there are differences between API endpoints.

[…]

Another issue that I hope doesn’t come up too often, is that APIs that have survived for a long time in the wild can sometimes have “versions” (if you’re lucky) or even potentially just have different representations for the same object based on which endpoint is requested. One way to handle this is to “smuggle” some context in to your decoding methods via the Decoder’s userInfo dictionary. Of course we would prefer to have a more structured contract for these and avoid any “Stringly Typed” interfaces, so we’ll want to leverage extensions to add a real interface to the JSONDecoder.

Previously: Swift.Codable, Swift 4: JSON With Encoder and Encodable.

1 Comment RSS · Twitter

[…] When JSONDecoder Meets the Real World, Swift.Codable, Swift 4: JSON With Encoder and […]

Leave a Comment