Jetpack Compose: Kotlinx serialization build JSON object

Introduction

This example demonstrates how to use Jetpack Compose with Kotlinx Serialization to build a JSON object and display it in an Android app. The code provides a foundational look at how to create a JSON structure directly within the code, serialize it into a human-readable format, and present it through a Compose UI. This example is helpful for Android developers working with data serialization in their apps, particularly when needing to create or manipulate JSON data for tasks like network requests, data storage, or in-app data handling.

In this article, we’ll explore the code step-by-step, breaking down each part to understand how it works. We'll start by creating the main activity, setting up the Compose content, defining a composable function for building and displaying the JSON, and formatting the JSON in a user-friendly way.

The Main Activity Setup

The MainActivity class extends ComponentActivity and serves as the entry point for the app. Inside onCreate, the setContent function initializes the UI using Jetpack Compose. The app’s theme is applied using the ComposeNetworkTheme, which wraps the app’s layout, providing a cohesive design and color scheme.

A Scaffold is used to create a basic layout structure for the app. Scaffold is a layout component in Jetpack Compose that enables the easy setup of a standard app layout with slots for elements like the top app bar, bottom navigation bar, and a central content area. Here, TopAppBar is set up within the topBar parameter, displaying a title that reads "Serialization Build Json Object". The main content of the screen is set by calling the MainContent composable function within the content parameter of the Scaffold.

Building the JSON Object with Kotlinx Serialization

The MainContent composable function is where the JSON object is built. First, the buildJsonObject function from kotlinx.serialization.json is used to create a JSON object. This object has three fields:

  • name, a string with the value "Jenny Jones"
  • age, an integer with the value 23
  • subject, a string with the value "Management"

By using buildJsonObject, developers can programmatically construct JSON structures in Kotlin, adding key-value pairs as needed. This is particularly useful for dynamically building JSON data from variables or user input within the app.

Serializing and Formatting the JSON Object

After the JSON object is built, the Json class from Kotlinx Serialization is used to format the JSON object into a string representation. By setting the prettyPrint option to true, the JSON is formatted in a readable way with indentation and line breaks, making it easier to view within the UI. The encodeToString method is then called to serialize the jsonObject into a string, storing it in the prettyObject variable.

Displaying the JSON Object in the UI

The final part of the MainContent function displays the serialized JSON string in the app's UI. A Column layout is used to organize the text display, with a padding of 24dp around the content for visual spacing. Inside the Column, a Text composable is used to display the prettyObject string. The style parameter of Text is set to MaterialTheme.typography.h6, which applies a headline style to the text, ensuring it is readable and visually appealing.

Summary

This example showcases the power and simplicity of combining Jetpack Compose with Kotlinx Serialization in an Android app. By building and displaying a JSON object directly in the app, developers gain insight into managing and formatting JSON data with ease. Jetpack Compose provides a responsive and modern UI, while Kotlinx Serialization enables efficient JSON construction and formatting.

For Android developers looking to handle JSON data within their apps, this example serves as a valuable guide to understanding the essentials of JSON serialization and UI display using Kotlin. The techniques shown here are scalable and can be adapted to various applications where JSON handling is required.


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 Object"
                                )
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


@Composable
fun MainContent() {
    val jsonObject: JsonObject = buildJsonObject{
        put("name","Jenny Jones")
        put("age",23)
        put("subject","Management")
    }

    val format = Json { prettyPrint = true }
    val prettyObject = format.encodeToString(jsonObject)

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