Using kotlin plugin 1.3.10 in Android Studio,
when I try to stringify a simple class' object to JSON, it wont compile:
This declaration is experimental and its usage must be marked with '@kotlinx.serialization.ImplicitReflectionSerializer' or '@UseExperimental(kotlinx.serialization.ImplicitReflectionSerializer::class)'
@Serializable data class Data(val a: Int, val b: Int)
val data = Data(1, 2)
val x = JSON.stringify(data)
However, giving a serialiser works:
val x = JSON.stringify(Data.serializer(), data)
I can't see anybody else having this problem, any idea what the problem is? I've set up using serialisation in gradle.build.
I import with:
import kotlinx.serialization.*
import kotlinx.serialization.json.JSON
The overload of StringFormat.stringify
which doesn't take in a serializer (SerializationStrategy
) is still experimental. If you view its definition (e.g. ctrl+click on it in the IDE) you'll see it looks as follows:
@ImplicitReflectionSerializer
inline fun <reified T : Any> StringFormat.stringify(obj: T): String = stringify(context.getOrDefault(T::class), obj)
Where that ImplicitReflectionSerializer
annotation is itself declared in that same file (SerialImplicits.kt
):
@Experimental
annotation class ImplicitReflectionSerializer
So because it's still experimental, you need to do exactly as the warning says, i.e. tell the compiler to allow the use of experimental features, by adding an annotation such as @UseExperimental...
where you're using it.
Note that the quick example shown on the kotlinx.serialization
GitHub repo's main readme shows that you need to pass in a serializer when calling stringify
.