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.
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
)
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-serialization:1.6.10"
}
}
plugins {
id 'kotlinx-serialization'
}
dependencies {
implementation 'org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.0'
}
- jetpack compose - Get text from url
- jetpack compose ktor - How to pass parameters
- jetpack compose ktor - How to post data
- jetpack compose - Kotlinx serialization lenient parsing
- jetpack compose - Kotlinx serialization allow special floating point values
- jetpack compose - Kotlinx serialization build json element
- jetpack compose - Kotlinx serialization decode josn element
- jetpack compose - How to use kotlin flow
- jetpack compose - Random number flow
- jetpack compose - Icon from vector resource