Skip to main content

Jetpack Compose: Kotlinx serialization lenient parsing

Kotlinx Serialization with Lenient Parsing in Jetpack Compose

In modern Android app development, parsing JSON data efficiently and accurately is essential, especially when dealing with dynamic or inconsistent JSON formats. Kotlinx Serialization offers robust tools to handle these tasks, including lenient parsing, which can simplify working with JSON that may not strictly follow conventional syntax. This article will explore how to leverage Kotlinx Serialization's lenient parsing mode in a Jetpack Compose project, offering an approachable solution for handling loosely formatted JSON data.

This Kotlin example centers on using Kotlinx Serialization with Jetpack Compose to parse a JSON string containing user information. The lenient mode in Kotlinx Serialization is activated to handle JSON that omits some structural rules, such as missing quotation marks around keys. The app displays the parsed information in a simple Compose UI, making it easy for developers to understand how lenient parsing can be implemented in a modern Android app setup.

Code Breakdown: Setting Up the Project Structure

The example starts with the MainActivity.kt file, the entry point of the application, where the Jetpack Compose UI and the main functionality are set up. The MainActivity class extends ComponentActivity, and in its onCreate function, the setContent method initializes the Compose UI. This is wrapped in a custom theme ComposeNetworkTheme, which defines the app's visual style. The UI layout is structured with a Scaffold component that provides a top bar labeled "Kotlinx Serialization Lenient Parsing" and a MainContent composable function to handle the primary content display.

Defining the Composable Content

The MainContent composable function is where the JSON parsing logic takes place. Inside this function, an instance of Json is created with isLenient = true. Setting isLenient to true enables Kotlinx Serialization to parse JSON data that might not strictly adhere to JSON standards, such as missing quotation marks around keys. The JSON string, userString, is defined as a variable and contains an object with three properties: firstName, lastName, and age. Due to lenient parsing, the JSON string can be parsed successfully even though it omits double quotes around the keys.

The decodeFromString function is then called on the format object, attempting to parse userString into an instance of a User data class. The parsed object is stored in userFromJsonString. If the parsing is successful, the userFromJsonString instance holds the values extracted from the JSON string, allowing the Compose UI to display them on the screen.

Displaying Parsed Data in the UI

Within the Column composable, the user’s name and age are displayed using the Text composable. The data is styled using MaterialTheme.typography.h5 to create a clean and readable presentation. The values userFromJsonString.firstName, userFromJsonString.lastName, and userFromJsonString.age are concatenated to form a full text string, showcasing the user’s full name and age on the screen. This setup demonstrates a practical way to use parsed JSON data within a Jetpack Compose UI.

Configuring the Build Files

The build configuration is essential to enable Kotlinx Serialization in the project. In build.gradle (project), the dependency for kotlin-serialization is added, while in build.gradle (app), the kotlinx-serialization plugin is applied to the module. The required JSON library, org.jetbrains.kotlinx:kotlinx-serialization-json, is also added to dependencies. This configuration allows the app to use Kotlinx Serialization's Json class for parsing JSON data.

Summary

This example demonstrates how to implement Kotlinx Serialization's lenient parsing mode in a Jetpack Compose Android application. By setting up lenient parsing, developers can parse loosely formatted JSON strings, such as those without quotes around keys. This approach offers flexibility and robustness in handling less strict JSON formats, which is particularly useful when consuming APIs with unpredictable data structures. The use of Jetpack Compose for displaying parsed data showcases a modern approach to building Android UIs, making this example a practical guide for Android developers aiming to enhance their data handling skills.


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.decodeFromString
import kotlinx.serialization.json.Json


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


@Composable
fun MainContent() {
    val format = Json{ isLenient = true }

    val userString = "{firstName: Farhana,lastName:Rahman,age:\"21\"}"
    val userFromJsonString = format.decodeFromString<User>(userString)

    Column(Modifier.fillMaxSize().padding(24.dp)) {
        Text(
            text = userFromJsonString.firstName +
                    " ${userFromJsonString.lastName}" +
                    "\nAge ${userFromJsonString.age}",
            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...