Handle (parsing) dynamic JSON response in Swift
I got a New Year’s eve “present” on December 30, 2019. Well it’s still too early even for New Year’s eve.
The “Present”
I’m facing with a dynamic JSON response from one same API call, something like this:
And sometimes like this when it has no result:
As you can see the value for “result” property can be an Object or a String. Your problem could be more than these two data types, maybe three, four, or more data types.
“That is an unpredictable result because we got it from an API call”
Current Situation
Currently, we use the Codable to parse the JSON to its respective model. And we have the Response struct with Generics so it can be used by another API calls like so:
Solve The Problem
We can make a Codable Enum representing those data types, like this:
And when it comes to the decode, we can parse it like this:
That’s it! Tell me your thought about this, if you want to correct me somewhere or maybe there is another effective way other than this feel free to write some response, cheers! 🥂