Introduction
In this article, we explore how to create a JSON array using Jetpack Compose in an Android application written in Kotlin. The example demonstrates how to use Kotlinx Serialization, a powerful and flexible library, to build JSON objects and arrays. JSON (JavaScript Object Notation) is widely used for data storage and communication between servers and mobile applications, and understanding how to manipulate JSON in Android can be essential for developers working with RESTful APIs or any data serialization.
The sample code creates a simple Compose UI layout that displays a JSON array built dynamically. We’ll walk through each part of the code, explaining how it uses Jetpack Compose’s composable functions and Kotlinx Serialization to construct and display JSON data in a human-readable format. By the end, you’ll have a good understanding of how to create, format, and display JSON arrays in a Kotlin-based Android project using Jetpack Compose.
Main Components of the Code
The code is organized within a single MainActivity.kt
file, starting with the MainActivity
class. This class is derived from ComponentActivity
, which provides the main entry point for an Android activity in a Compose project. The onCreate
method, an essential part of the Android activity lifecycle, is overridden here to set up the content of the application.
In the onCreate
method, the setContent
block initializes the user interface with the ComposeNetworkTheme
, a custom theme created for this application. Inside the ComposeNetworkTheme
, a Scaffold
is used to structure the layout. Scaffold
is a layout structure in Jetpack Compose that allows you to set up commonly used UI components such as a TopAppBar
, which here displays a simple title: "Serialization Build Json Array."
Building the JSON Array with Kotlinx Serialization
The core of the application is in the MainContent
composable function, where we use Kotlinx Serialization to build a JSON array. The JsonArray
instance is created using the buildJsonArray
function, which allows for the dynamic addition of JSON objects to the array. Each object in the array is created with addJsonObject
, a function that allows you to set key-value pairs representing different fields. Here, five objects are added to the JSON array, each representing a simple attribute: firstName
, lastName
, dept
, age
, and salary
. This structure simulates a basic data model you might encounter in real applications, such as an employee profile.
In this array, each addJsonObject
entry adds a key-value pair for a specific attribute, making it easy to build a collection of structured data entries. The use of put
within addJsonObject
allows us to set the fields for each JSON object, creating a JSON array ready for display or further processing.
Formatting and Displaying the JSON Array
Once the JSON array is constructed, we move on to formatting it in a readable way. The Json
object, configured with prettyPrint = true
, formats the JSON for readability by adding indentation and line breaks. This is helpful for debugging and displaying JSON data directly to the user. The encodeToString
method is used to convert the JSON array to a formatted string.
Finally, in the Column
composable, the formatted JSON string (prettyArray
) is displayed in the UI using a Text
composable. The Modifier.fillMaxSize()
and padding(24.dp)
ensure that the content fills the screen with some padding around the edges. The MaterialTheme.typography.h6
style gives the text a structured, clear appearance that matches the app’s theme.
Summary
This example demonstrates how to use Jetpack Compose and Kotlinx Serialization to create and display a JSON array in an Android app. By structuring the UI with Jetpack Compose and formatting JSON data with Kotlinx Serialization, we can easily present structured data in a clean, readable format. The use of buildJsonArray
and addJsonObject
simplifies the JSON creation process, making it more readable and maintainable.
This approach is useful for applications that need to construct JSON data on the fly or interact with APIs, where JSON is the primary data format. With Kotlin’s and Jetpack Compose’s streamlined syntax, Android developers can create powerful and dynamic user interfaces that handle JSON data efficiently.
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 Array"
)
}
)
},
content = { MainContent()}
)
}
}
}
}
@Composable
fun MainContent() {
val jsonArray: JsonArray = buildJsonArray{
addJsonObject { put("firstName","Jenny") }
addJsonObject { put("lastName","Jones") }
addJsonObject { put("dept","Accounting") }
addJsonObject { put("age",30) }
addJsonObject { put("salary",1200) }
}
val format = Json { prettyPrint = true }
val prettyArray = format.encodeToString(jsonArray)
Column(Modifier.fillMaxSize().padding(24.dp)) {
Text(
text = prettyArray,
style = MaterialTheme.typography.h6
)
}
}
- jetpack compose - Get screen width height in dp
- jetpack compose - Get screen layout direction
- jetpack compose - How to hide status bar
- jetpack compose - How to hide navigation bar
- jetpack compose - Get text from url
- jetpack compose ktor - How to pass parameters
- jetpack compose - Kotlinx serialization alternative json names
- jetpack compose - Kotlinx serialization allow special floating point values
- jetpack compose - Kotlinx serialization decode josn element
- jetpack compose - How to use kotlin flow
- jetpack compose - Random number flow