Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type mismatch when serializing data class

Tags:

kotlin

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?

like image 292
user2233706 Avatar asked Nov 27 '20 20:11

user2233706


1 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
like image 81
IR42 Avatar answered Nov 13 '22 06:11

IR42