Open In App

Use Kotlinx Serialization Library to Parse JSON Data From Network Call

Last Updated : 13 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

We generally use the famous GSON, Moshi library to parse JSON data coming from api/network calls using Retrofit. But now it becomes the old way for Kotlin projects as JetBrains (creator company of kotlin) released kotlinx.serialization Kotlin-first multiplatform JSON data serialization library. kotlinx.serialization is written in pure Kotlin, and available on all Kotlin Multiplatform targets, including Kotlin/Native and Kotlin/JS. It let’s effortlessly serialize/de-serialize JSON into type-safe Kotlin objects, and vice versa.

Why use Kotlin Serialization Library over Moshi and Gson:

  • Faster runtime performance than Gson and Moshi in reflective mode through code generation.
  • Faster build times than Moshi through the use of a compiler plugin rather than an annotation processor.
  • Better support for Kotlin’s type system compared to Gson, including support for nullable and default values.
  • Support for many encoding formats through the use of separate library modules.

In this article, we’ll see how we can use it in our project to parse JSON data coming from api/network calls using the Retrofit library. 

Adding Kotlin Serialization library & Retrofit Converter for Kotlin Serialization:

First, open the project-level build.gradle and add the Kotlin Serialization classpath in the dependencies block:

dependencies {
  // Other classpath declarations
  classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
}

Now, open your app-level build.gradle and apply the plugin in the plugins block at the top of the file:

plugins {
    // Other plugins...
    id 'kotlinx-serialization'
}

Next, add dependencies in the dependencies block:

dependencies {
  // Other dependencies...
  
  // Kotlinx Serialization dependency
  implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.2.2"
  
  // Retrofit kotlin-serialzation-converter
  // It lets Retrofit use the Kotlin Serialization library to convert API requests and responses.
  implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0"
}

Now, let’s first see how we can map our JSON data into Kotlin data/pojo class  using kotlinx.serialization:

We took an example of the below JSON object which we will convert into kotlin data/pojo class.

{
    “course_name”:”Modern Android Development”,
    “course_img”:”https://media.geeksforgeeks.org/wp-content/cdn-uploads/20210215201419/Android-Tutorial.png”,
    “courseMode”:”Online Batch”,
    “courseTracks”:”8 Tracks”
    "is_course_freely_available": true
}

The Kotlin Serialization library generates serializers for classes annotated with @Serializable. A serializer is a class that handles an object’s serialization and deserialization for every class annotated with @Serializable.And the @SerialName annotation lets you specify a custom name for your Kotlin object. So, if you don’t want to use the same JSON field name for your Kotlin object… then use the @SerialName(“actual_json_field_name_here”) annotation to map an object with a different name than the JSON field name.

Kotlin Data class Or POJO class:

Kotlin




@Serializable
data class ExampleResponse(
    @SerialName("course_name"
    val name: String,
    @SerialName("course_img"
    val courseImage: String,
    // we won't use @SerialName 
    // on those objects
    // whose names will be exactly 
    // same as of json field name.
    val courseMode: String,
    val courseTracks: String,
    @SerialName("is_course_freely_available"
    val isFree: Boolean,
)


In the above code, we have mapped JSON data in Kotlin data class.

Creating JSON Converter Factory for Retrofit

Now, Wherever you will build your Retrofit instance, build that like this:

Kotlin




//------Creating & adding Retrofit-Kotlinx-Serialization-Converter Factory-------//
     
// Creating kotlinx serialization 
// converter factory for Retrofit
val contentType = "application/json".toMediaType()
val kotlinxConverterFactory = Json.asConverterFactory(contentType)
    
// Adding this converter factory here 
// while building retrofit object.
Retrofit.Builder()
  .addConverterFactory(converterFactory)
  .baseUrl("your_base_url")
  .build()


The above code creates kotlinxConverterFactory object as a converter factory that uses JSON and adds it to the Retrofit instance. So that Retrofit can communicate with the API through JSON objects. And that’s it, this way you can easily use Kotlinx.Serialization library with Retrofit instead of GSON & Moshi to parse JSON data.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads