Livefront
Published in

Livefront

kotlinx.serialization: JSON deserializer with a fallback

In a perfect world, the consumer and producer of an API would always be in lockstep, only changing with each other and adhering to the strictest of contracts. Alas, we live in the real world, and it helps to be a bit pessimistic when controlling data falls just outside of your grasp.

If you are the consumer of an API, sometimes there might be a reasonable fallback if deserialization goes horribly wrong. In other words, we want a KSerializer that will fall back to some default value if deserialization fails:

This extension of KSerializer is modeled heavily after KSerializer.nullable: it augments an existing KSerializer with a bit of extra functionality. In this case, we wrap the deserialization call in a try/catch, returning the provided default value if any exception occurred during deserialization.

Now, putting it to use: for forwards-compatibility reasons, it can be helpful to allow enums to take a default UNKNOWN value. Like the name suggests, we want any unknown value to be turned into UNKNOWN instead of causing an error:

With the fallback serializer above, that’s all there is to it!

October 2020 edit: Updated to match kotlinx.serialization 1.0.0 interface.

Alex works at Livefront, where we always try to leave data a little bit cleaner than when we get it.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alex Vanyo

Alex Vanyo

Android DevRel Engineer @ Google