'How does Kotlin's Json.decodeFromString work without a first DeserializationStrategy argument?
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 {
Solution 1:[1]
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.
Solution 2:[2]
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"}""")
}
Solution 3:[3]
Add below import worked for me
import kotlinx.serialization.decodeFromString
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Byte Welder |
| Solution 2 | |
| Solution 3 | JS84 |
