Member-only story
Why and How to Use Kotlin’s Native Serialization Library
The simplest way to serialize a JSON response in Android

Takeaway From the Article
By the end of this article, you’ll learn why Kotlin's team created a new serialization library despite having many advanced libraries like Moshi and Gson. Along with that, you’ll also learn how to use a native serialization library, and if you’re patient enough to read to the end, you might also know the hidden features of native serialization. Read on to learn about them.
Why the Kotlin Team Created a New Serialization Library
We have many famous and effective serialization libraries out there, like Moshi from Square and Gson from Google. But the Kotlin team decided to create a brand new native serialization library for Kotlin. The question is, why?
Serialization libraries like Moshi and Gson are Java libraries that use reflections, which is fine for Android development. Kotlin is not restricted to Android(JVM); it supports JavaScript(JS) and IOS(native) development. Reflections sure as hell won’t work with Kotlin.js and native modules. Moreover, using reflections in Android is also a downside.
Apart from multi-platform support and using reflections in serialization, there is one more drawback with Java serialization libraries: they won’t support default value variables in Kotlin. To understand it clearly, let’s start with a simple data class as shown below:
data class SimpleExample(val data : String,
var optionalData : String = "empty")
When we try to parse JSON with only data
node, then the optionalData
value is changed to null
instead of assigning a default value empty
as declared in the data class. This is a big problem because when a variable is declared without question mark, then the Kotlin compiler will guaranty that the variable is never going to be null
, but normal Java serialization libraries aren’t aware of that. This type of functionality conflict results in unexpected behavior of the app.
So the Kotlin team decided to create a serialization library that works with all the platforms it’s supporting and is also without…