Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlinx-serialization class marked @Serializable does not have the .serializer() extension function

I have the following data class

@Serializable
data class Income(val id: String, 
                  val description: String, 
                  val amount: Int, 
                  val Time: Date, 
                  val userId: String)

now when I try to use the .serializer() function it says that the .serializer() is not defined for Income class so my project doesn't compile.

    val response = Json.stringify(Income.serializer(), Incomes)
    call.respond(HttpStatusCode.OK,response) 

I Looked twice on the documentation in the readme.md. Even watched the announcement video from KotlinConf

Did anyone have the same problem. What am i doing wrong??

Edit:

I tried to just copy paste the samples from the readme.md and had the same problem.

import kotlinx.serialization.*
import kotlinx.serialization.json.*

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

fun main() {
    // Json also has .Default configuration which provides more reasonable settings,
    // but is subject to change in future versions
    val json = Json(JsonConfiguration.Stable)
    // serializing objects
    val jsonData = json.stringify(Data.serializer(), Data(42))
    // serializing lists
    val jsonList = json.stringify(Data.serializer().list, listOf(Data(42)))
    println(jsonData) // {"a": 42, "b": "42"}
    println(jsonList) // [{"a": 42, "b": "42"}]

    // parsing data back
    val obj = json.parse(Data.serializer(), """{"a":42}""") // b is optional since it has default value
    println(obj) // Data(a=42, b="42")
}

This does not compile as well in my code. I'm currently using Kotlin 1.3..61 and kotlinx-serialization-runtime 0.14.0

like image 269
yonBav Avatar asked Feb 29 '20 11:02

yonBav


2 Answers

In addition to the kotlinx-serialization-runtime dependency you also need to add the plugin

plugins {
    kotlin("multiplatform") // or kotlin("jvm") or any other kotlin plugin
    kotlin("plugin.serialization") version "1.4.10"
}

with the same version as Kotlin itself.

like image 71
Alexey Romanov Avatar answered Sep 24 '22 14:09

Alexey Romanov


I had a similar problem that my Navigation Drawer XML file didn't recognize my serializable class, for that I had to extend the java.io.Serializable myself, bit for kotlin it was fine:

@Serializable
data class Income(val id: String, 
                  val description: String, 
                  val amount: Int, 
                  val Time: Date, 
                  val userId: String) : java.io.Serializable
like image 23
Amin Keshavarzian Avatar answered Sep 23 '22 14:09

Amin Keshavarzian