Tuesday, March 29, 2022

jetpack compose - Kotlinx serialization allow special floating point values

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.text.style.TextOverflow
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 = "Serialization Allow Special" +
                                            " Floating Point Values",
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis
                                )
                            }
                        )
                    },
                    content = { MainContent()}
                )
            }
        }
    }
}


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

    val product = Product(name = "School Bag", price = Double.NaN)
    val productString = format.encodeToString(product)

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


@Serializable
data class Product(
    val name: String,
    val price: Double
)