Kotlin Serialization Library

Kotlin has recently released a library for serialization. To put things in perspective, before this there was no serialization lib provided by kotlin but you could use any platform supported serialization libraries with Kotlin classes(eg. Gson for JVM/Android)

But that’s where Kotlin’s serialization library is different, it’s cross platform and supports multiple formats. The whole lib is built on top of Kotlin’s multiplatform concept.

Currently kotlinx.serialization supports three formats

  • JSON
  • CBOR
  • Protobuf

And platforms are JVM and JS, but others should get added soon as Kotlin/native becomes mature.

Let’s take a look at JSON

Marking @Serializable will make a class serializable.

stringify will convert a serializable object to JSON string.

parse will convert well formed json back to a data class.

Parsing has multiple options like

In above example, json string doesn’t have quotes. We can parse such json with JSON.unquoted. This can be helpful during debugging.

Here’s a definition of all such properties available

Additional Properties

Often our data objects have properties which could be optional. For example, there could be extra properties which we initialize on client side which server may not provide while fetching the json. Similarly there may be properties which may or may not be present in json. Fortunately the lib handles both cases.

Optional — This value will considered during serialization/deserialization. but if not present, it won’t break serialization.

Transient — This value will not be considered during serialization/deserialization. But if present in json, it will cause an exception.

If you’re not sure about consistency of values in json, using JSON.nonstrict might be a good idea to avoid exceptions

Class variables can have different names than the name of key in json. Just annotate using @SerialName

Additional Utilities

There are few utilities also available out of box

Mapper

Mapper can convert a object to a map — straightforward.

ValueTransformer

Transformer allows custom transformation on each value of object.

There are more override methods for float, boolean etc in ValueTransform.

Custom Serialization

The lib allows you to define your own serialization scheme if required.

Full doc here

Code gist: https://gist.github.com/jitinsharma/8805cf63ba3b371b657531d55d3fd6c5

Thanks for reading!

Please provide your thoughts in comments and don’t forget to clap if you liked the story.

Android and UX @gojektech

The (retired) Pub(lication) for Android & Tech, focused on Development