Thursday, March 31, 2022

jetpack compose - Kotlinx serialization build json object

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.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 Object"
                                )
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


@Composable
fun MainContent() {
    val jsonObject: JsonObject = buildJsonObject{
        put("name","Jenny Jones")
        put("age",23)
        put("subject","Management")
    }

    val format = Json { prettyPrint = true }
    val prettyObject = format.encodeToString(jsonObject)

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