Type mismatch when serializing data class

Viewed 2128

I'm following this example to serialize a data class. When I do so, I get this build error:

Type mismatch: inferred type is Data but SerializationStrategy<TypeVariable(T)> was expected

Here's my code:

import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable

@Serializable
data class Data(val a: Int, val str: String = "str")

fun main() {
    println(Json.encodeToString(Data(42)))
}

Since I am using the @Serializable annotation, shouldn't I have the right data type? How can I serialize the data class?

3 Answers

The function that only requires the value parameter is implemented as an extension function, so you need to add import

import kotlinx.serialization.encodeToString

To make it clear: instead of

import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable

you must write

import kotlinx.serialization.json.Json
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString

I was using the wrong encodeToString() function. It has to be kotlinx.serialization.encodeToString, not the one from kotlinx.serialization.json.Json

Please check the imports. The ones below come from kotlin serialization and needs just the string and the object respectively.

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
Related