Skip to main content

How to exclude null values while serializing Kotlin objects to JSON using GSON in Kotlin Android

How to exclude null values while serializing Kotlin objects to JSON using GSON in Kotlin Android.

Here's a step-by-step tutorial on how to exclude null values while serializing Kotlin objects to JSON using GSON in Kotlin Android.

Step 1: Add GSON Dependency

First, you need to add the GSON dependency to your project's build.gradle file. Open the build.gradle file and add the following line to the dependencies block:

implementation 'com.google.code.gson:gson:2.8.6'

Step 2: Create a Kotlin Data Class

Next, create a Kotlin data class that represents the object you want to serialize to JSON. For example, let's say you have a Person class with various properties:

data class Person(
val id: Int,
val name: String?,
val age: Int?
)

Step 3: Configure GSON

Create an instance of GSON and configure it to exclude null values during serialization. You can do this by creating a GsonBuilder and calling the serializeNulls() method with a value of false. Here's an example:

val gson = GsonBuilder()
.serializeNulls(false)
.create()

Step 4: Serialize Kotlin Object to JSON

To serialize a Kotlin object to JSON using GSON, simply call the toJson() method on the GSON instance and pass in the object you want to serialize. Here's an example:

val person = Person(1, "John Doe", null)
val json = gson.toJson(person)

In this example, the age property is set to null, but it will be excluded from the JSON output because we configured GSON to exclude null values.

Step 5: Verify the JSON Output

To verify that the null values are excluded from the JSON output, you can print the json string to the console or log it. Here's an example:

Log.d("JSON", json)

The output should be:

{"id":1,"name":"John Doe"}

As you can see, the age property is not included in the JSON output.

Step 6: Deserialize JSON to Kotlin Object

If you want to deserialize the JSON back to a Kotlin object, you can use the fromJson() method on the GSON instance. Here's an example:

val personObject = gson.fromJson(json, Person::class.java)

In this example, the json string is deserialized back to a Person object. The age property will be null in the personObject because it was excluded from the JSON output.

And that's it! You have learned how to exclude null values while serializing Kotlin objects to JSON using GSON in Kotlin Android.