Tuesday, March 29, 2022

jetpack compose - Kotlinx serialization decode from string

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 Decode From String")
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


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

    val employeeJsonString = "{ firstName: Jenny, lastName: Jones," +
            "dept: Accounting, salary:1200, age:28}"

    val employee = format.decodeFromString<Employee>(employeeJsonString)

    Column(Modifier.fillMaxSize().padding(24.dp)) {
        Text(
            text = "${employee.firstName} ${employee.lastName}" +
                    "\nDepartment: ${employee.dept}" +
                    "\nSalary: ${employee.salary} USD" +
                    "\nAge: ${employee.age}",
            style = MaterialTheme.typography.h5
        )
    }
}


@Serializable
data class Employee(
    val firstName: String,
    val lastName: String,
    val dept: String,
    val salary: Int,
    val age: Int
)