https://kotlinlang.org logo
Join Slack
Powered by
# serialization
  • d

    Distractic

    07/10/2025, 1:45 AM
    Hello everyone I'm creating an app in Kotlin with Spring. I configure everything to use Kotlin Serialization instead of Jackson and that works. However, I would like to generate the OpenApi doc. But I can't find a plugin (gradle) or dependencies that support the Kotlin Serialization annotation for my Spring controller's DTO. So two questions for you: Is there a plugin or dependency that support Kx-serializable (If not for the first question) Do you recommend me to go back on Jackson due to the lack of support of Kotlin Serializable with Spring Have a good day
    u
    • 2
    • 1
  • d

    dave08

    07/10/2025, 12:49 PM
    It seems like KotlinX Serialization doesn't yet support kotlin.time.Instant or am I missing something?
    c
    • 2
    • 4
  • j

    joseph_ivie

    07/10/2025, 3:15 PM
    I was disappointed by existing CSV parsing libraries, so we built our own here at Lightning Kite and I figure it's time to start seeing if we can help someone else with the work we've done. https://github.com/lightningkite/kotlinx-serialization-csv-durable This CSV encoder/decoder features sequence streaming and has (AFAIK) total support for KotlinX Serialization via fallback formats - in other words, if KotlinX serialization can serialize it, it will work with this format in both directions.
    👍🏼 1
    👍 1
    e
    • 2
    • 5
  • p

    Pavel Kazlovich

    07/14/2025, 11:58 AM
    Is there a way to get a contextual serializer for an already serializable type using
    serializer<@Contextual MyType>
    ? For now it seems to work only if
    MyType
    is not serializable.
    đź‘€ 1
    r
    • 2
    • 2
  • j

    Jaap Beetstra

    07/14/2025, 12:49 PM
    I just submitted a bug I encountered when using
    JsonDecoder.decodeJsonElement
    within an array in a custom deserializer when combined with
    Json.decodeFromJsonElement
    . Does my write up make sense, or did I mess up somewhere?
  • s

    shikhar

    07/17/2025, 4:05 AM
    Facing issues when trying to serialise data classes with js primitive types, seems like an issue with the generated js serializer code. Serialization attempts always throw a
    ClassCastException
    due to an instanceof check kotlinx-ser adds which won’t work with js primitive types. Issue with sample code: https://github.com/Kotlin/kotlinx.serialization/issues/3048 Please help if anyone knows of a solve
  • c

    CLOVIS

    08/12/2025, 3:32 PM
    Is it possible to apply the KotlinX.Serialization plugin only to test sources (
    commonTest
    ,
    jvmTest
    …)?
    s
    r
    • 3
    • 4
  • j

    joseph_ivie

    08/13/2025, 5:20 PM
    I wrote a really cursed snippet of code that allows you to get or copy/set individual fields by index on any struct with generated serializer. It's within an order of magnitude of performance to direct gets and copies, at least within my test case. Anybody interested in a copy? I'm using it to write conditions/modifications for a database system based on KotlinX serialization.
  • c

    CLOVIS

    08/14/2025, 8:44 PM
    Hi! I'm seeing this error:
    Copy code
    > Thrown during execution:
    java.lang.AssertionError: Class with incorrect id found: expected opensavvy/ktmongo/sync/studies/AggregationProjectUnionWithKt$AggregationProjectUnionWith$2$Customer, actual opensavvy/ktmongo/sync/studies/AggregationProjectUnionWithKt$AggregationProjectUnionWith$2$Customer
    	at kotlin.reflect.jvm.internal.impl.load.kotlin.JavaClassDataFinder.findClassData(JavaClassDataFinder.kt:29)
    	at kotlin.reflect.jvm.internal.impl.serialization.deserialization.ClassDeserializer.createClass(ClassDeserializer.kt:44)
    	at kotlin.reflect.jvm.internal.impl.serialization.deserialization.ClassDeserializer.access$createClass(ClassDeserializer.kt:27)
    	at kotlin.reflect.jvm.internal.impl.serialization.deserialization.ClassDeserializer$classes$1.invoke(ClassDeserializer.kt:29)
    Is this something you've ever seen? The class in question is
    Copy code
    @Serializable
    	data class Customer(
    		val _id: String,
    		val name: String,
    		val biography: String?,
    	)
    declared locally in a lambda. I thought it could be an incremental compilation issue of some kind, but it reproduces in CI.
    j
    • 2
    • 1
  • h

    Hunter

    08/17/2025, 7:59 PM
    Is there a way to annotate type parameters as not needing to be serializable to serialize a class in kotlinx-serialization? Ex.
    Copy code
    @Serializable
    class Foo<T> { /*...*/ }
    I would want to communicate to the compiler that the type parameter
    T
    is not needed during serialization, and so it doesn't need to be marked as contextual at the use-site. Currently I have to do this everywhere that I use `Foo`:
    Copy code
    interface Bar {
       val foo: Foo<@Contextual Bar>,
       // ...
    }
    âž• 1
    j
    • 2
    • 1
  • c

    Colton Idle

    08/23/2025, 4:50 PM
    is the name "kotlinx.serialization" or "kotlin serialization"? i always called it kotlinx.serialization, but only today noticed "org.jetbrains.kotlin.plugin.serialization"
    e
    • 2
    • 1
  • r

    rnett

    08/23/2025, 8:03 PM
    Hey there, I'm trying to implement a custom Decoder that enables
    decodeSequentially
    . I'm having issues getting it to handle primitive properties with default values - it appears that the generated serializer calls
    decodeStringElement
    even for properties with defaults, which gives me no way to handle the default. In non-sequential decoding I handle this by just not returning the index if the default value should be used - is there a way to do something similar for sequential decoding, or any way at all to signal the default value should be used?
  • a

    Abhimanyu

    08/31/2025, 3:55 AM
    Is this warning expected?
    Copy code
    The type "<1>$*" is used in a field rule. The characters in this type are legal for the JVM, but unlikely to originate from a source language. Maybe this is not the rule you are looking for.
    proguard
    file from the lib.
    Copy code
    # Keep `Companion` object fields of serializable classes.
    # This avoids serializer lookup through `getDeclaredClasses` as done for named companion objects.
    -if @kotlinx.serialization.Serializable class **
    -keepclassmembers class <1> {
        static <1>$* Companion;
    }
    
    # rest of the file
    h
    • 2
    • 2
  • f

    Fred Bowker

    09/03/2025, 4:28 PM
    I’m getting the following warning “this declaration is opt-in and its usage should be marked with @kotlinx.serialization.InternalSerializationApi” whenever a class is marked with @Serializable, not sure why this warning is showing up as Serializable isn’t experimental opt-in
  • f

    Fred Bowker

    09/03/2025, 5:05 PM
    reading through some previous messages and I can hide the warning by adding a lint with
    Copy code
    <?xml version="1.0" encoding="UTF-8"?>
    <lint>
        <issue id="UnsafeOptInUsageError" severity="ignore">
            <option name="opt-in" value="kotlinx.serialization.InternalSerializationApi" />
        </issue>
    </lint>
    but not sure why this is necessary, or whether this is an issue with intellij
  • v

    v79

    09/14/2025, 4:21 PM
    I may be wrong, but I think kotlin.time.Instant and kotlinx.datetime.Instant serialize differently. My API sends a kotlinx.datetime.Instant and it appears in Json as "2025-09-06T103224.608Z" . I think. Maybe. Can anyone confirm if the two Instant classes serialize differently?
    h
    • 2
    • 5
  • u

    ursus

    09/18/2025, 10:52 AM
    Is there a way to have a sort of
    Unknown
    sealed class child, that will be a fallback when all other classes don't match? (With annotations only? I know I can have a custom serializer a wire it up manually)
    Copy code
    @Serializable
    sealed class Item {
    
       @SerialName("A")
       @Serializable
       data class ChildA(..) : Item()
    
       @Serializable
       data class Unknown : Item() <--------
    }
    m
    • 2
    • 2
  • m

    Martin Scotta

    09/24/2025, 5:28 AM
    Hi all, we are seeing some serialization issues and we would like to hear from leaders and the broad community. Full details here: https://github.com/temporalio/sdk-java/issues/2665 The TLDR is our kotlin project is having challenges integrating with Jackson/Gson serialization. Are these compatible to each other? Is it possible to write a custom Jackson/Gson adapter that entirely delegates encode/decode to kotlin?
    g
    • 2
    • 15
  • s

    Said Shatila

    10/01/2025, 5:48 PM
    Hey has anyone faced this issue error while building ?
    đź§µ 2
    • 1
    • 1
  • r

    Richard Schielek

    10/01/2025, 10:30 PM
    Is there a more elegant way of doing this? I know a sealed super type with polymorphic serialization would also do it, but it feels awkward if there is only one implementation.
    Copy code
    import kotlinx.serialization.EncodeDefault
    import kotlinx.serialization.Required
    import kotlinx.serialization.Serializable
    import kotlinx.serialization.json.Json
    
    @Serializable
    data class SomeEvent(
        val subject: String,
    ) {
        @EncodeDefault
        @Required
        private var type = "SOME_EVENT"
    
        init {
            require(type == "SOME_EVENT") { "'type' field of SomeEvent must be 'SOME_EVENT' but was '$type'" }
        }
    }
    
    fun main() {
        println(Json.encodeToString(SomeEvent("foo"))) // {"subject":"foo","type":"SOME_EVENT"}
        println(Json.decodeFromString<SomeEvent>("""{"subject": "foo", "type": "SOME_EVENT"}""")) // SomeEvent(subject=foo)
        println(
            try {
                Json.decodeFromString<SomeEvent>("""{"subject": "bar", "type": "OTHER_EVENT"}""")
            } catch (e: IllegalArgumentException) {
                e.message
            }
        ) // 'type' field of SomeEvent must be 'SOME_EVENT' but was 'OTHER_EVENT'
    }
    e
    • 2
    • 4
  • j

    Joaquim Puyo

    10/06/2025, 6:55 AM
    Hello, In a Kotlin multiplatform SDK, when trying to send a POST request and building http request body, I have some random crash EXC_BAD_ACCESS(KERN_INVALID_ADDRESS)
    Copy code
    Thread
    0x6bea58 serialize + 11 (CollectRequestBodyDto.kt:11)
    0x6882e4 encodeSerializableValue + 69 (StreamingJsonEncoder.kt:69)
    0x6623e8 serialize + 69 (CollectionSerializers.kt:69)
    0x6882e4 encodeSerializableValue + 69 (StreamingJsonEncoder.kt:69)
    0x6bdda8 serialize + 6 (CollectRequestBodyDto.kt:6)
    0x6882e4 encodeSerializableValue + 69 (StreamingJsonEncoder.kt:69)
    0x678c68 encodeToString + 32 (JsonStreams.kt:32)
    0x675f40 invokeSuspend + 95 (SerialFormat.kt:95)
    0x676208 serialize + 54 (KotlinxSerializationConverter.kt:54)
    0x63eef4 invokeSuspend + 40 (ContentConverter.kt:40)
    0x640000 invoke + 142 (ContentNegotiation.kt:142)
    0x6dc9c4 invoke + 1 ([K][Suspend]Functions:1)
    0x635fa4 invokeSuspend + 78 (KtorCallContexts.kt:78)
    0x6361c8 invoke + 77 (KtorCallContexts.kt:77)
    0x6d6a0c invoke + 1 ([K][Suspend]Functions:1)
    0x6032ac loop + 120 (SuspendFunctionGun.kt:120)
    0x602f8c proceed + 78 (SuspendFunctionGun.kt:78)
    0x62b8c0 invokeSuspend + 41 (PipelineContext.kt:41)
    0x62bbd0 invoke + 149 (HttpCallValidator.kt:149)
    0x6d6a0c invoke + 1 ([K][Suspend]Functions:1)
    0x6032ac loop + 120 (SuspendFunctionGun.kt:120)
    0x602f8c proceed + 78 (SuspendFunctionGun.kt:78)
    0x6316d0 invokeSuspend + 41 (PipelineContext.kt:41)
    0x631918 invoke + 40 (HttpRequestLifecycle.kt:40)
    0x6dc8f0 invoke + 1 ([K][Suspend]Functions:1)
    0x631c20 invokeSuspend + 27 (HttpRequestLifecycle.kt:27)
    0x632130 invoke + 20 (HttpRequestLifecycle.kt:20)
    0x6d6bb4 invoke + 1 ([K][Suspend]Functions:1)
    0x631804 invoke + 40 (HttpRequestLifecycle.kt:40)
    0x6d6a0c invoke + 1 ([K][Suspend]Functions:1)
    0x6032ac loop + 120 (SuspendFunctionGun.kt:120)
    0x602f8c proceed + 78 (SuspendFunctionGun.kt:78)
    0x603158 execute + 98 (SuspendFunctionGun.kt:98)
    0x60181c execute + 74 (Pipeline.kt:74)
    0x61c7e8 invokeSuspend + 193 (HttpClient.kt:193)
    0x63c414 invokeSuspend + 190 (HttpClient.kt:190)
    0x6d1510 invokeSuspend + 111 (HttpStatement.kt:111)
    0x6d17c8 invoke + 42 (TheWireRemoteDataSource.kt:42)
    0x6dc8f0 invoke + 1 ([K][Suspend]Functions:1)
    0x6d0d18 invokeSuspend + 67 (TheWireRemoteDataSource.kt:67)
    0x6d09c0 invokeSuspend + 65 (TheWireRemoteDataSource.kt:65)
    0x6d0be4 sendEvents + 63 (TheWireRemoteDataSource.kt:63)
    0x6cfd58 invokeSuspend + 94 (TheWireQueueEventsCollector.kt:94)
    0x6cffc8 sendRequest + 97 (TheWireQueueEventsCollector.kt:97)
    0x6d01e4 invokeSuspend + 72 (TheWireQueueEventsCollector.kt:72)
    0x6d0720 invoke + 66 (TheWireQueueEventsCollector.kt:66)
    0x6d6938 invoke + 1 ([K][Suspend]Functions:1)
    0x5281e4 invokeSuspend + 72 (IntrinsicsNative.kt:72)
    0x526fa8 resumeWith + 50 (ContinuationImpl.kt:50)
    0x5c605c run + 1 (Result.kt:1)
    0x5c6f60 run + 115 (LimitedDispatcher.kt:115)
    0x5d182c invokeSuspend + 106 (MultithreadedDispatchers.kt:106)
    0x526fa8 resumeWith + 50 (ContinuationImpl.kt:50)
    0x5c605c run + 1 (Result.kt:1)
    0x5a6108 processNextEvent + 15 (ObjectiveCUtils.kt:15)
    0x5ce1e0 runBlocking + 49 (EventLoop.common.kt:49)
    0x5d1eb0 $<bridge-UNN>invoke(){} + 119 (MultithreadedDispatchers.kt:119)
    0x6d4d08 invoke + 1 ([K][Suspend]Functions:1)
    0x785fe0 Worker::processQueueElement(bool) + 6900
    0x785ab0 (anonymous namespace)::workerRoutine(void*) + 5572
    0x606c _pthread_start + 136
    0x10d8 thread_start + 8
    I have omitted some fields here, but basically it seems that the crash is produced when trying to serialize the sealed class 'Default':
    Copy code
    @Serializable
    internal data class CollectRequestBodyDto(
        @SerialName("events") val events: List<EventDto>
    )
    
    @Serializable
    internal data class EventDto(
        ...
        @SerialName("data") val data: DataDto,
    )
    
    
    @Serializable
    internal sealed class DataDto {
        @Serializable
        data class Default(
                @SerialName("category") val category: String? = null,
                @SerialName("event") val event: String? = null,
                ...
        ) : DataDto()
    
        @Serializable
        data class Search(
            ...
        ) : DataDto()
    }
    Looking at the stack trace, it seems that the crash is located at this line: https://github.com/Kotlin/kotlinx.serialization/blob/71b5d5ee99f953b60756c4aaa2ac8e12c3fae605/formats/json/commonMain/src/kotlinx/serialization/json/internal/StreamingJsonEncoder.kt#L69
    Copy code
    override fun <T> encodeSerializableValue(serializer: SerializationStrategy<T>, value: T) {
            encodePolymorphically(serializer, value) { discriminatorName, serialName ->
                polymorphicDiscriminator = discriminatorName   --> Crash is located here
                polymorphicSerialName = serialName
            }
        }
    To provide more context, this is working without issues in Android and failing randomly in iOS, and it is executed inside a background process that is sending analytics events. To solve the situation, I will try to avoid sealed classes and build the json in some other way (like buildJsonObject), but I would like to know any hint about the root cause of this issue. This is working for 99% of the users, but randomly failing from time to time. I am not able to reproduce the issue but I see error logs in crashlytics.... Any hint? Thanks!
  • m

    Md Anas Shikoh Shikoh

    10/06/2025, 9:56 AM
    Copy code
    @Keep
    data class RatingData(
        @SerializedName("show_nudge") val showNudge: Boolean,
        @SerializedName("is_app_rated") val isAppRated: Boolean,
    )
    this is my response class I wanted to know if backend sends null in anyone of these values, right now my app is not crashing but from what i know it should crash. Anyone has any idea about this, i think this is something related to Boolean because for other types it definitely crashes.
  • l

    Lilian GALLON

    10/08/2025, 7:22 AM
    Hi there, is there a way to change the way an Enum is serialized / deserialized when you can't modify it? I want to change the way the deserialization works to transform an unknown enum value to "MyEnum.OTHER" instead of throwing an exception. I implemented my own KSerializer(MyEnum), registered it in
    Json { serializersModule = SerializersModule { contextual(MyEnum::class, MyEnumSerializer) } }
    , but kotlinx.serialiaztion keeps using
    kotlinx.serialization.internal.EnumSerializer
    instead of the serializer I registered. Is there a way to force the use of my serializer ?
    âś… 1
    e
    • 2
    • 2
  • t

    Travis Haagen

    10/10/2025, 10:58 PM
    Hello! I put up a PR to add support for "untagged null values in CBOR", and was hoping to discuss how it could potentially move forward. Untagged null is supported by the CBOR spec and needed for a project I am working on. https://github.com/Kotlin/kotlinx.serialization/pull/3074 cc: @Filipp Zhinkin
    f
    r
    • 3
    • 3
  • b

    Bernhard

    10/16/2025, 2:01 PM
    is there a reason why xml serialization is not part of kotlinx but ktor?
    h
    s
    • 3
    • 3
  • s

    Slackbot

    10/22/2025, 10:59 AM
    This message was deleted.
    h
    c
    • 3
    • 2
  • c

    Colton Idle

    10/22/2025, 6:41 PM
    I'm using kotlinx.serialization in my android library (first time developing a library). Does anyone know if I need to supply any r8 rules for consumers of the library? I'm not proguarding/r8ing my library, but if an app uses r8 and uses my library will it still know to retain those Serialized fields? according to the docs https://github.com/Kotlin/kotlinx.serialization?tab=readme-ov-file#android i shouldn't have to add anything in my app, but now I'm curious if its any different if its an android library?
    e
    • 2
    • 3
  • c

    CLOVIS

    10/25/2025, 1:17 PM
    Is there an easy way to write something like
    Copy code
    @Serializable
    data class Foo(
        val date: @SerializeAsUnixSeconds Instant,
    )
    where it would serialize as
    Copy code
    data class Foo(
        val date: Int, // number of seconds since UNIX epoch
    )
    ? I know I could create a custom serializer for
    Foo
    , but there are many classes and fields where I need this and I don't want to create custom serializers for all of them. (same question for serializing a
    Duration
    as an
    Int
    number of seconds)
    h
    e
    +3
    • 6
    • 16
  • b

    Bernhard

    10/30/2025, 12:56 PM
    how do I serialize/deserialize an arbitrary JSON object? I've got a field that can have arbitrarily nested JSON data answer: MapString, JsonElement?
    âś… 1
    r
    • 2
    • 1
  • c

    CLOVIS

    10/30/2025, 8:06 PM
    Copy code
    interface Foo
    
    @Serializable
    data object Bar : Foo
    // Impossible to make this class serializable because its parent is not serializable and does not have exactly one constructor without parameters
    I'm surprised this is forbidden. I would have expected it to serialize correctly as an empty JSON object.
    âž• 1
    e
    • 2
    • 1