Monday, March 28, 2022

jetpack compose - Kotlinx serialization ignore unknown keys

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 Ignore Unknown Keys")
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


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

    val userString = "{" +
            "firstName: Anamika," +
            "middleName: Khan," +
            "lastName:Rahman,age:\"23\"," +
            "class:Eight}"
    val userFromJsonString = format.decodeFromString<User>(userString)

    Column(Modifier.fillMaxSize().padding(24.dp)) {
        Text(
            text = userFromJsonString.firstName +
                    " ${userFromJsonString.lastName}" +
                    "\nAge ${userFromJsonString.age}",
            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'
}