Jetpack Compose: Kotlinx serialization build JSON element

Introduction

This example showcases how to leverage Kotlin’s Jetpack Compose and Kotlinx Serialization libraries to build and display JSON elements in a structured and readable format. Using the Json and buildJsonObject classes, this code constructs a JSON object, serializes it with a specified format, and presents it on-screen in a Jetpack Compose UI. This approach is valuable for Android developers who want to generate, manipulate, and display JSON data directly in Compose without relying on external APIs or complex data transformation layers.

In this example, you’ll see how the structure is organized around a MainActivity that contains the UI setup, and a MainContent function that builds and formats a JSON object. The code employs modern Android development practices, such as using Scaffold and TopAppBar for layout and MaterialTheme for styling, making it a great example of Kotlin's seamless integration with Jetpack Compose.

Detailed Breakdown

The main entry point, MainActivity, extends ComponentActivity to provide a lifecycle-aware activity context suitable for setting up the Compose UI. The onCreate function is overridden to call setContent, which initiates the Compose UI with a custom theme defined by ComposeNetworkTheme. Inside setContent, a Scaffold layout is used, which provides a flexible structure that makes it easy to manage the app bar, floating actions, or other screen elements. The TopAppBar contains a simple Text component displaying the title "Serialization Build Json Element."

The actual JSON creation occurs in the MainContent function, a composable responsible for defining the data structure displayed on the screen. In this function, the buildJsonObject function creates a JSON object with a few key-value pairs: firstName, lastName, and age. Within this structure, two nested objects are added—dept as a nested object representing a department and skills as a JSON array of individual skill objects. Each skill object contains a language key, demonstrating how Kotlinx Serialization enables a straightforward approach to building structured, nested JSON data.

After defining the JSON object, the Json class’s encodeToString method is used to convert it to a human-readable string format with pretty-print enabled. The formatted JSON string, prettyElement, is ready to be displayed on the screen. In this example, the Column composable arranges UI elements vertically. The JSON string is rendered within a Text composable, using the Material Theme’s typography.h6 style to ensure that the text is clearly readable.

The UI layout specified in MainContent makes use of Modifier.fillMaxSize() and Modifier.padding(24.dp) to ensure that the content takes up the full screen and includes adequate padding around the edges. These modifiers provide control over how components are displayed in the layout, adhering to Compose's declarative style.

Summary

This example demonstrates the effective use of Kotlinx Serialization alongside Jetpack Compose to build, format, and display JSON data within an Android app. By combining JSON handling with Compose's declarative UI model, the code efficiently generates structured data and visually presents it in a clean, formatted layout. This approach allows developers to focus on JSON data without dealing with additional complexities or unnecessary dependencies.

With this setup, Android developers can easily manipulate JSON data directly in Compose, making it highly suitable for apps requiring dynamic content generation, configuration storage, or data visualization. This example serves as a foundation for further JSON manipulation and formatting techniques, showcasing the flexibility of Kotlin's serialization capabilities and the elegance of Jetpack Compose for building modern Android UIs.


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.encodeToString
import kotlinx.serialization.json.*


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


@Composable
fun MainContent() {
    val element = buildJsonObject {
        put("firstName","Jenny")
        put("lastName","Jones")
        put("age",30)
        putJsonObject("dept"){
            put("name","Development")
        }
        putJsonArray("skills"){
            addJsonObject { put("language","Kotlin") }
            addJsonObject { put("language","Java") }
            addJsonObject { put("language","C#") }
        }
    }

    val format = Json { prettyPrint = true }
    val prettyElement = format.encodeToString(element)

    Column(Modifier.fillMaxSize().padding(24.dp)) {
        Text(
            text = prettyElement,
            style = MaterialTheme.typography.h6
        )
    }
}
More android jetpack compose tutorials