Tuesday, March 29, 2022

jetpack compose - Kotlinx serialization encode defaults

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("Kotlinx Serialization Encode Defaults")
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


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

    val employee = Employee(firstName = "Jenny", lastName = "Jones")
    val employeeString = format.encodeToString(employee)

    Column(Modifier.fillMaxSize().padding(24.dp)) {
        Text(
            text = employeeString,
            style = MaterialTheme.typography.h5
        )
    }
}


@Serializable
data class Employee(
    val firstName: String,
    val lastName: String,
    val dept: String = "Accounting",
    val salary: Int? = null
)