user2233706
user2233706

Reputation: 7207

Type mismatch when serializing data class

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?

Upvotes: 22

Views: 6650

Answers (4)

import kotlinx.serialization.decodeFromString

Was the solution for me

Upvotes: 0

IR42
IR42

Reputation: 9682

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

Upvotes: 67

Narendra_Nath
Narendra_Nath

Reputation: 5173

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

Upvotes: 2

user2233706
user2233706

Reputation: 7207

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

Upvotes: 2

Related Questions