Decoding a model with different JSON using Decodable
De-serialize or Parsing the different JSON and map to same model with Decodable
Scenario
I know this is not everyday scenario that we face but there can be many situation where you may have implement this kind of behavior instead of duplicating same contextual models with weird names and have redundant code. Example
- An App accessing user data from two different sources with different JSON object even though the user is same in those different sources. Example: A super app providing services from different services provided user is having account on those services
In scenario like this you will be working with different API endpoint of these services and parse the JSON.
So the question is how will achieve this with Decodable?
Let’s Start Decoding
In the below example gist, I have added two scenarios of user JSON we will receive in our app from different scenarios. Now what we did is
- We created a user object which implements
Decodable
with keys we need to parse in it. - We created two different
CodingKeys
for our case as we are expecting two different sources, In this caseServiceOneCodingKeys
andServiceTwoCodingKeys
which handle the user object for this two different services. - Now comes the Important part where we implement custom
init(from decoder: Decoder)
, In this we implement custom strategy to decode our user object with two different JSON, The implementation is straight forward as you can see we first decode it first with ServiceOne container and verify any variable in this caseuserId
and if we found itnil
we move towards to second container. - Lastly if none of container works we send
fatalError
in this case, We can also send crash report to verify the unknown issues.
Thank you for reading
I hope this article helps you, You can copy the gist in Xcode playground and have a hands on with your custom scenarios.