Monday, March 28, 2022

jetpack compose - Kotlinx serialization pretty print

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(
                                    text = "Kotlinx Serialization Pretty Print"
                                )
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


@Composable
fun MainContent() {
    val format = Json { prettyPrint = true }
    val user = User("Jenny", "Jones", 32)

    Column(Modifier.fillMaxSize().padding(16.dp)) {
        Text(
            text = format.encodeToString(user),
            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'
}