Search code examples
kotlinkotlinx.serialization

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


Solution

  • 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.