Hello Kotlin Serialization, goodbye Gson!

Tram Ho

What is Kotlin Serialization?

In today’s Android world, many famous and efficient libraries for serialization have been released. The most famous of which is probably Gson – a library from the owner of the Android operating system – Google. But even so, the Kotlin development team decided to launch a new library of their own, called Kotlin Serialization, exclusively for Kotlin. Why is that ?

The existing serialization libraries like Gson, Moshi … are Java libraries using Java’s reflection (*) feature, which is quite suitable for Android development. But Kotlin is not only limited to Android (JVM), it also supports other platforms like JavaScript (Kotlin / JS) and iOS (Kotlin / Native) … reflection only works on JVM is definitely impossible. Exam when working with JS and Native platforms. Also, using reflection in Android is another big drawback (causing memory leak).

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or “introspect” upon itself, and manipulate internal properties of the program. For example, it’s possible for a Java class to obtain the names of all its members and display them.

Summary: Reflection is a feature in Java. It allows an executing Java program to check or “endorse” itself and manipulate the program’s internal properties. For example, a Java class could take the names of all of its members and display them.

Source: https://www.oracle.com/technical-resources/articles/java/javareflection.html

Aside from the need for multiplatform support and the use of reflections, there is another downside to Java serialization libraries that they don’t support default values ​​in Kotlin. To understand this clearly, look at the example below:

When we parse a JSON with only one data property, the optionalData property will be set to null instead of the default value "empty" as defined in the data class. This is a big deal because when a variable is declared as non-nullable (without the? Sign?) The Kotlin compiler will always make sure that the variable will never be null , but Java libraries Serialization is not aware of that. The result from this function conflict is a lot of undesirable behavior going on in the application.

So the Kotlin team decided to create a serializaition library that will work on all of the platforms it is supporting without using reflection.

Integrate Kotlin Serialization into the project

To use the Kotlin Serialization library, we need to integrate both the Gradle Plugin and the runtime library. Gradle plugin will generate code to parse JSON without using any reflection. Meanwhile, the runtime library will use this code to serialize the data classes.

To integrate the Kotlin Serialization plugin, we need to declare classpath in the top-level build.gradle file as follows:

If using Kotlin DSL (build.gradle.kts) then:

Then declare the plugin in the app level:

New style:

Using Kotlin DSL:

Then you can add the implementation in the dependencies block:

How to use Kotlin Serialization with data class

Kotlin Serialization can be used quite quickly since this is a native library of the Kotlin team. We simply add the @Serializable annotation right above the desired class. Type as follows:

It is done! You don’t need to add annotation to every property of the class like it does for Gson.

However, if you want to set a custom name to fit with name attributes from JSON, for example, you can add @SerialName annotations for each attribute:

Integrate Kotlin Serialization into Retrofit 2

We are all familiar with Retrofit converters for Gson, Moshi … right. Likewise, a converter is also required for Kotlin Serialization. There are a number of third-party libraries that support this. But for the most prestige, perhaps you should use the library of Mr. JakeWharton (a famous engineer from Square, author of Timber, Butter-Knife, ThreeTen ABP …).

Add dependencies:

Then add the Retrofit declaration place:

Useful hidden features

Compile-time safety

This is for when you are dealing with complex serializations, for example when you have classes nested inside a response data class.

Of course you need to add annotation @Serialization for class ProfileResponse , but if you forget to add annotation for class Profile , why? Will the application crash at runtime? Or will you have to manually check to make sure all nested classes have been annotated?

Fortunately, you don’t have to be that hard. The application will never crash and you do not need to manually check Kotlin Serialization is a compile-time safe. It will display an error if you haven’t added annotation on any of the nested classes, no matter how deep your class structure is.

The @Transient and @Optional annotations

  • Transient : By assigning this annotation to a property in the data class, we are specifying that this field should be completely ignored by the Serializer.
  • Optional : By assigning this annotation to the data class, we are specifying this field as optional so we cannot break the process if this field is not found in the response. We can also assign a default value like below:

    Both of these two annotations are very reasonable, but somehow Java libraries lack them.

Share the news now

Source : Viblo