Jetpack Compose: Kotlinx serialization not encode null values

Introduction

In Android development, handling JSON data is essential, particularly when working with APIs. Jetpack Compose, combined with Kotlin’s kotlinx.serialization library, offers a powerful way to encode and decode data for efficient and readable data management. However, there may be cases where encoding null values is unnecessary, and excluding them can make the resulting JSON cleaner. This code example demonstrates how to disable the encoding of null values using kotlinx.serialization in a Jetpack Compose application.

The following example features a straightforward user interface displaying a JSON-encoded string. It uses Jetpack Compose's declarative UI approach and highlights the configuration settings needed to prevent null values from being encoded into JSON data, making the output compact and more readable.

Code Explanation: MainActivity Setup

In this example, MainActivity is a ComponentActivity subclass that serves as the entry point of the application. The onCreate function, which initializes the activity, is overridden to set up the content view. Using setContent, we apply the ComposeNetworkTheme and define a Scaffold component. The Scaffold contains a TopAppBar with a simple title, "Serialization Not Encode Null Values," and a MainContent composable function that provides the main content for the screen.

The structure of MainActivity showcases the use of Jetpack Compose’s Scaffold, which allows a flexible arrangement of common layout elements like top bars, bottom bars, and floating action buttons. This setup makes the code modular and easy to expand or modify if additional components are required in the future.

MainContent Composable

The core of this example is the MainContent composable function, where JSON encoding is performed. Inside this function, a Json instance is created with specific configurations: prettyPrint is set to true for a readable JSON format, and explicitNulls is set to false, which ensures that null values are excluded from the output. This configuration is important for creating a clean JSON string without unnecessary null entries, which can save storage space and make data transmission more efficient.

An instance of the User data class is then created with specific values for the firstName, lastName, and age properties. In this case, lastName is set to null, allowing us to observe how the explicitNulls setting affects the output. The format.encodeToString(user) function call encodes the User object into a JSON string, omitting the lastName field due to its null value.

Displaying the JSON Data

Finally, a Column composable with padding and fill size modifiers arranges the output on the screen. Inside the Column, a Text composable is used to display the encoded JSON string in a readable format. The MaterialTheme.typography.h5 style is applied to the text, giving it a distinctive and visually appealing format.

This layout allows for easy adjustments to the presentation, as more UI elements or different styling options could be added to the Column composable to enhance the visual structure. The composable’s modular design keeps the code organized and makes it simpler to manage or expand in response to potential UI changes.

Summary

This example demonstrates a clean and effective way to handle JSON serialization in a Jetpack Compose application using Kotlin's kotlinx.serialization library. By disabling the encoding of null values, the JSON output becomes more concise and efficient, saving bandwidth and storage resources. This approach is particularly useful in applications where null data is frequent but unnecessary for processing.

Using Jetpack Compose with kotlinx.serialization and simple settings like explicitNulls, developers can create responsive UIs and optimize data handling seamlessly. This example provides a foundation for building more complex data serialization and display features in modern Android applications.


MainActivity.kt

package com.cfsuman.composenetwork

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.cfsuman.composenetwork.ui.theme.ComposeNetworkTheme
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json


class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ComposeNetworkTheme {
                Scaffold(
                    topBar = {
                        TopAppBar(
                            title = {
                                Text("Serialization Not Encode Null Values")
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


@OptIn(ExperimentalSerializationApi::class)
@Composable
fun MainContent() {
    val format = Json{
        prettyPrint = true
        // null values are not encoded into json
        explicitNulls = false
    }

    val user = User(firstName = "Suman", lastName = null, age = 20)
    val userString = format.encodeToString(user)

    Column(Modifier.fillMaxSize().padding(24.dp)) {
        Text(
            text = userString,
            style = MaterialTheme.typography.h5
        )
    }
}


@Serializable
data class User(
    val firstName: String,
    val lastName: String?,
    val age: Int
)
More android jetpack compose tutorials