I'm very new to Kotlin and am curious what magic allows this code to work:
@Serializable
data class Box(val s: StringHolder?)
val deserialized = Json.decodeFromString<Box>(string)
When the function definition seems to require an initial argument before the encoded JSON string.
public final override fun <T> decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T {
Add below import works for me
import kotlinx.serialization.decodeFromString
That method is currently part of an experimental API in SerialFormat.kt :
It is an extension function with the following interface:
@OptIn(ExperimentalSerializationApi::class)
public inline fun <reified T> StringFormat.encodeToString(value: T): String
You need to enable experimental APIs to be able to use it.
To use this you need to import import kotlinx.serialization.decodeFromString
. But because this is an experimental API , you also need to mark your class or method with @ExperimentalSerializationApi
. But to enable experimental switches you also need to add an compiler by languageSettings.optIn("kotlin.RequiresOptIn")
.
build.gradle.kts
plugins {
kotlin("jvm") version "1.5.31"
kotlin("plugin.serialization") version "1.5.31"
}
kotlin.sourceSets.all {
languageSettings.optIn("kotlin.RequiresOptIn")
}
test.kts
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.SerialFormat
import kotlinx.serialization.json.Json
import kotlinx.serialization.decodeFromString
@Serializable
data class Box(val s: String = "")
@OptIn(ExperimentalSerializationApi::class)
fun readJson(){
val deserialized = Json.decodeFromString<Box>("""{"s" : "Hallo"}""")
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.