Expanding on Generic Json Parsing

Thu Apr 12 2018 | Mark Struzinski

---

Expanded JSON Parsing with Generics

In the last post, I went over a very simple way to use generics when parsing a small object that had a value type determined at runtime. Today, I’d like to expand on that concept a bit and show how I implemented that concept into a parent struct that contained arrays of this object.

Keep in mind I’m doing a lot of force unwrapping here because I’m in a test case. This is not a safe practice in production code! Moving on from this, I needed an object that would represent the setting for a property, including all potentials values for each version number of the app. The buisiness requirement here is to use the default value unless it is overridden. A default value is overridden if the optional array of valuesByVersion contains a setting that matches the current app version.

With the new Decodable protocol, anytime you want to run custom logic when decoding an object (rather than just mapping properties to values), you need to implement init(from decoder: Decoder). After this point you, are reponsible for initializing all non-optional properties of your model object prior to exiting the method. I’ll use the init method here to check for the specific version of the running app instance, and see if that version is in the list of PropertyEntry objects coming back in the list. If it is, then I know there is a custom setting for this version of the app and I’ll use it. This is accomplished by passing in some context to the JSON Decoder.

Decode an initial defaultValue from the single entry in the base JSON response

Try to decode an array of PropertyEntry objects from the response

If an array exists, check the userInfo dictionary attached to the decoder. If an appVersion exists in here, use it as a filter value.

Assign the result of all that logic to the defaultValue of the model object

Note

Like a lot of other objects in Cocoa Touch APIs, you are allowed to attach a userInfo dictionary to the decoder. For this decoding scenario, I’m attaching the current app version to the decoder that parses this object. When creating this dictionary, the keys are of type CodingUserInfoKey.