Handle (parsing) dynamic JSON response in Swift

Michael Agustian
Blibli.com Tech Blog
2 min readFeb 3, 2020
Photo by Olav Ahrens Røtne on Unsplash

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:

The Question?

But how we can determine the Generics when we try to decode the JSON, since the return is unpredictable?

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! 🥂

--

--

Blibli.com Tech Blog
Blibli.com Tech Blog

Published in Blibli.com Tech Blog

Articles on Blibli.com's engineering, culture, and technology. Written and curated by the very people who build Blibli.com. The views expressed are those of the authors and don't necessarily reflect those of Blibli.com.