Tuesday, March 29, 2022

jetpack compose - Kotlinx serialization handle null values

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("Serialization Handle Null Values")
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


@Composable
fun MainContent() {
    val format = Json{
        isLenient = true
        // handle null values
        coerceInputValues = true
    }

    val userString = "{ firstName: Anamika," +
            "lastName: null, age: 19 }"
    val user = format.decodeFromString<User>(userString)

    val userString2 = "{ firstName: Sofia," +
            "lastName: Khatun, age: 27 }"
    val user2 = format.decodeFromString<User>(userString2)

    Column(Modifier.fillMaxSize().padding(24.dp)) {
        Text(
            text = "${user.firstName} ${user.lastName}" +
                    "\nAge ${user.age}",
            style = MaterialTheme.typography.h5
        )

        Spacer(modifier = Modifier.height(12.dp))
        Text(
            text = "${user2.firstName} ${user2.lastName}" +
                    "\nAge ${user2.age}",
            style = MaterialTheme.typography.h5
        )
    }
}


@Serializable
data class User(
    val firstName: String,
    val lastName: String = "Default last name",
    val age: Int
)