Skip to main content

Jetpack Compose: Kotlinx serialization pretty print

Introduction

In this guide, we will walk through an example of setting up pretty-printed JSON serialization in an Android app using Jetpack Compose and Kotlinx Serialization. This example demonstrates how to create a simple Android application where data is encoded into a readable JSON format and displayed in the user interface using Jetpack Compose. JSON serialization is a powerful way to represent objects in a human-readable format, which is helpful for debugging, logging, and API communication.

The example code is well-structured, leveraging modern Android libraries and tools, such as Jetpack Compose for building the UI and Kotlinx Serialization for JSON formatting. We'll break down each part of the code, explaining how the user interface, data model, and serialization are set up. By the end of this description, you’ll understand how these components work together and how to integrate pretty-printed JSON serialization into your own Compose-based Android applications.

Understanding the MainActivity Class

The MainActivity class extends ComponentActivity, which is the base class for Jetpack Compose-based activities in Android. Inside onCreate, setContent is called to set up the Compose UI for the activity. The ComposeNetworkTheme function wraps the entire UI, applying a consistent look and feel across the app. In this case, Scaffold is used to provide basic material structure, including a top app bar with the title "Kotlinx Serialization Pretty Print."

The Scaffold component allows us to create a layout with slots for the app bar, floating action buttons, and other content areas. Here, MainContent is provided as the main content for the screen, where our serialized JSON string will be displayed.

MainContent Composable

The MainContent composable function is where the JSON serialization and data display take place. First, it creates an instance of Json with the prettyPrint property set to true. This setting ensures that the JSON output will be formatted with indentation and line breaks, making it easy to read.

Inside MainContent, a User object is created with sample data—first name "Jenny," last name "Jones," and age 32. The JSON representation of this User object is generated by calling format.encodeToString(user), which converts the user data into a pretty-printed JSON string. This formatted string is then displayed on the screen using a Text composable, styled with MaterialTheme.typography.h5 for clear and readable text.

Data Model with @Serializable

The User data class represents a simple user model with three properties: firstName, lastName, and age. The class is annotated with @Serializable, enabling it to be serialized and deserialized by Kotlinx Serialization. This annotation automatically generates the necessary code to transform User objects into JSON and vice versa, making it easy to work with JSON data in Kotlin.

Dependency Setup in Gradle

To use Kotlinx Serialization in this project, we need to add specific dependencies in the Gradle build files. In the project-level build.gradle, the kotlin-serialization plugin is included in the classpath. Then, in the app-level build.gradle, we apply the plugin kotlinx-serialization and add the dependency for kotlinx-serialization-json library version 1.3.0. This setup enables serialization functionality throughout the app.

Summary

This example combines Kotlinx Serialization and Jetpack Compose to create a simple Android app that pretty-prints JSON. With the prettyPrint option enabled, JSON data is displayed in a clean, human-readable format, making it especially useful for debugging or logging. The integration of Kotlinx Serialization with the @Serializable annotation allows for automatic handling of JSON conversions, making data manipulation straightforward.

Overall, this example demonstrates how to structure a Compose-based Android project with serialization, from setting up dependencies to creating the UI. By following this guide, you can enhance your app with pretty-printed JSON serialization, improving readability and data handling capabilities.


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.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(
                                    text = "Kotlinx Serialization Pretty Print"
                                )
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


@Composable
fun MainContent() {
    val format = Json { prettyPrint = true }
    val user = User("Jenny", "Jones", 32)

    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Text(
            text = format.encodeToString(user),
            style = MaterialTheme.typography.h5
        )
    }
}


@Serializable
data class User(
    val firstName: String,
    val lastName: String,
    val age: Int
)
build.gradle [project]

buildscript {
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-serialization:1.6.10"
    }
}
build.gradle [app]

plugins {
    id 'kotlinx-serialization'
}


dependencies {
    implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0'
}
More android jetpack compose tutorials

Popular posts from this blog

Restricting Jetpack Compose TextField to Numeric Input Only

Jetpack Compose has revolutionized Android development with its declarative approach, enabling developers to build modern, responsive UIs more efficiently. Among the many components provided by Compose, TextField is a critical building block for user input. However, ensuring that a TextField accepts only numeric input can pose challenges, especially when considering edge cases like empty fields, invalid characters, or localization nuances. In this blog post, we'll explore how to restrict a Jetpack Compose TextField to numeric input only, discussing both basic and advanced implementations. Why Restricting Input Matters Restricting user input to numeric values is a common requirement in apps dealing with forms, payment entries, age verifications, or any data where only numbers are valid. Properly validating input at the UI level enhances user experience, reduces backend validation overhead, and minimizes errors during data processing. Compose provides the flexibility to implement ...

jetpack compose - TextField remove underline

Compose TextField Remove Underline The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text. The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField. The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc. Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorC...

jetpack compose - Image clickable

Compose Image Clickable The Image widget allows android developers to display an image object to the app user interface using the jetpack compose library. Android app developers can show image objects to the Image widget from various sources such as painter resources, vector resources, bitmap, etc. Image is a very essential component of the jetpack compose library. Android app developers can change many properties of an Image widget by its modifiers such as size, shape, etc. We also can specify the Image object scaling algorithm, content description, etc. But how can we set a click event to an Image widget in a jetpack compose application? There is no built-in property/parameter/argument to set up an onClick event directly to the Image widget. This android application development tutorial will demonstrate to us how we can add a click event to the Image widget and make it clickable. Click event of a widget allow app users to execute a task such as showing a toast message by cli...