How does Kotlin's Json.decodeFromString work without a first DeserializationStrategy argument?

Viewed 5211

I'm very new to Kotlin and am curious what magic allows this code to work:

From https://github.com/Kotlin/kotlinx.serialization/blob/e2e764a132c8eebd31208120774baf9a71ec23c7/formats/json/commonTest/src/kotlinx/serialization/SerializerForNullableTypeTest.kt

@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.

https://github.com/Kotlin/kotlinx.serialization/blob/e2e764a132c8eebd31208120774baf9a71ec23c7/formats/json/commonMain/src/kotlinx/serialization/json/Json.kt

public final override fun <T> decodeFromString(deserializer: DeserializationStrategy<T>, string: String): T {
3 Answers

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"}""")
}
Related