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

    Nikky

    04/11/2025, 7:22 AM
    so.. xn32/Json5k has been archived a while ago (and i just noticed).. does anyone know of a good json5 lib for serialization? this is for config files with comments and such
    h
    • 2
    • 3
  • a

    Andrey Tabakov

    04/21/2025, 1:13 PM
    What do you think about this? https://github.com/Kotlin/kotlinx.serialization/issues/2993
    a
    • 2
    • 2
  • r

    rocketraman

    04/25/2025, 1:37 PM
    I am experimenting with implementing "typed ids" similar to those used by Stripe. See article https://dev.to/stripe/designing-apis-for-humans-object-ids-3o5a. I've played around with various implementations but nothing comes out very clean and elegant on both the data model side and the kotlinx-serialization side. Anyone have any thoughts / design ideas? Ideally I'd like to have the serializable class be as simple as
    data class FooBar(val id: TypedUuid<FooBar>, …)
    and the serialization of
    id
    be as simple as
    fb_<uuid>
    .
    p
    • 2
    • 4
  • m

    Marcello Galhardo

    04/28/2025, 8:29 PM
    Since there’s a reified
    serializer<T>()
    that throws if no serializer is found, why isn’t there a
    serializerOrNull<T>()
    as well? I know there’s a
    serializerOrNull(KType)
    , but as I understand it,
    typeOf<T>()
    relies on reflection and has performance implications.
    e
    e
    • 3
    • 5
  • s

    S.

    05/01/2025, 10:27 AM
    I need a
    JsonObject
    to specify response formats of a third party lib, is it somehow possible to retrieve a JsonObject from a
    @Serializable class MyClass
    without writing the mapping by hand?
    g
    • 2
    • 2
  • z

    Zyle Moore

    05/11/2025, 3:02 AM
    Is there some type to represent anything that's Serializable? For context, this isn't about an existing format like Json or Cbor. I'm trying to make a generic wrapper, but keep ending up at making the type
    Any
    and getting an error that no serializer for
    Any
    was found. I understand why, I'm just not quite sure how to get what I want with that being true. By default, something like
    @Serializable data class Point(val x: Int, val y: Int)
    will eventually make a call to
    beginStructure
    , two calls to
    encodeInt
    , and a call to
    endStructure
    . If I replace
    Int
    with any other primitive type, like
    Short
    ,
    Double
    ,
    Float
    ,
    Long
    , the two calls in the middle will be the appropriate method for that type,
    encodeShort
    ,
    encodeFloat
    , etc. I'm looking for something that behaves exactly the same way, but the encode method it calls is
    encodeSerializableValue
    instead of
    encodeInt
    . Or maybe even
    encodeInline
    . This example though doesn't use generics, so perhaps it's easier for the generator to map confidently. In my generic wrapper example, I have a
    @Serializable @JvmInline value class FieldValue<T : Any>(val value: T) : FieldToken
    The idea being a very thin wrapper around some serializable value, that I can treat as a subtype of
    FieldToken
    . I have a containing class
    @Serializable data class Record(val header: RecordHeader, val fields: List<FieldValue<Any>>)
    which is where my trouble comes in. I want to be able to serialize, roughly, something that looks like
    Copy code
    [ "TES4", [ flags, formId, timestamp, versionControl, recordVersion, unknown ] ],// RecordHeader
      [ "HEDR", [ 1.7, 0, 0 ] ],// // FieldValue<(Float, Short, Short)>
      [ "CNAM", "Zymus" ],// FieldValue<NullTerminatedString>
      [ "SNAM", "TES4 JSON Tuple Example" ],// FieldValue<NullTerminatedString>
      [ "MAST", "Skyrim.esm" ],// FieldValue<NullterminatedString>
      [ "DATA", 0 ],// FieldValue<Long>
      [ "MAST", "Update.esm" ],// FieldValue<NullTerminatedString>
      [ "DATA", 0 ],// FieldValue<Long>
      [ "MAST", "Hearthfires.esm" ],// FieldValue<NullTerminatedString>
      [ "DATA", 0 ],// FieldValue<Long>
      [ "ONAM", [ 0 ] ],// FieldValue<List<Int>>
      [ "INTV", 0 ],// FieldValue<Int>
      [ "INCC", 0 ]// FieldValue<Short>
    c
    • 2
    • 2
  • m

    martmists

    05/19/2025, 6:08 PM
    How can I create a custom serializer for a string value that counts as null if the string is empty? In my case I have a
    class UuidSerializer : KSerializer<UUID>
    but I want
    ""
    to be decoded as
    null
    rather than a UUID value.
    e
    h
    • 3
    • 11
  • l

    Lukasz Kalnik

    05/20/2025, 8:16 AM
    I have a backend response, which is just a plain string (not wrapped in a JSON object, so like this:
    "12345"
    ). Do I need to configure something special in the Kotlinx Serialization
    Json
    object for it to be parsed?
    e
    • 2
    • 3
  • r

    rad

    05/24/2025, 5:03 PM
    I've been getting this exception whilst trying to decode any class with fields with type arguments:
    Copy code
    java.lang.AbstractMethodError: 'kotlinx.serialization.KSerializer[] kotlinx.serialization.internal.GeneratedSerializer.typeParametersSerializers()'
    Full stacktrace: https://pastes.dev/UaaPnH2ZPY My code:
    Copy code
    @Serializable
    @SerialName("data")
    public data class DataMatcher(
      public val predicate: Map<String, String>
    ) : ServerMatcher { ... }
    where
    ServerMatcher
    is a sealed serializable interface. I'm using 1.8.1.
    ➕ 1
    a
    s
    • 3
    • 4
  • y

    y

    05/27/2025, 9:22 AM
    hey, on IntelliJ with K2 I'm getting lots of
    Serializer has not been found for type 'MyType'
    . this is not an error for us with our current environment, and seems there are no plans to add a serializer for these. can I suppress the error?
  • a

    Andrey Tabakov

    05/28/2025, 10:13 AM
    What is the easiest way to migrate concrete serializers to polymorphic ones, while still supporting previously serialized old objects? My old impl:
    Copy code
    @Serializable
    data class MyConcreteDataClass(val name: String)
    
    @Serializable
    data class MyCommonClass(val value: MyConcreteDataClass)
    I want to support a new implementation while also maintaining compatibility:
    Copy code
    @Serializable
    sealed interface AllDataClasses {
        val name: String
    }
    
    @Serializable
    data class MyConcreteDataClass(override val name: String): AllDataClasses
    
    @Serializable
    data class MyNewConcreteDataClass(override val name: String): AllDataClasses
    
    @Serializable
    data class MyCommonClass(val value: AllDataClasses)
    May be there is a way to provide a fallback serializer if legacy object doesn’t point to polymorphic object?
    e
    b
    • 3
    • 23
  • z

    Zyle Moore

    05/30/2025, 2:09 AM
    I think I'm missing something on polymorphic deserialization. I have an archive-like file format, with elements like Files and Folders. A Folder can contain Files, or other Folders, or a mix of both. All entries have a header. The type of entry is encoded within that header. If the first 4 bytes of of the header are
    GRUP
    , it is a Folder. If it is anything else, it is a File. During serialization, it tries to encode the full name of the type. I don't seem to be able to customize the discriminator behavior, and during deserialization, I get errors like > kotlinx.serialization.SerializationException: Invalid index in polymorphic deserialization of unknown class > Expected 0, 1 or DECODE_DONE(-1), but found -3 Ultimately, I'm wondering how to model this. My current method has been a
    List<FolderChild>
    , but I don't think there's enough type information to do what I'm trying to do.
    b
    • 2
    • 3
  • c

    CLOVIS

    06/22/2025, 8:50 AM
    I'm confused by the way to implement
    AbstractEncoder
    . Let's say I want to serialize:
    Copy code
    @Serializable
    class User(val id: Int)
    From what I understand, KotlinX.Serialization will call:
    Copy code
    MyEncoder.beginStructure(User.serializer.serialDescriptor).apply {
        encodeInt(1234)
        endStructure(User.serializer.serialDescriptor)
    }
    What I don't understand is: when
    encodeInt(1234)
    is called, how do I know it's the field
    id
    and not another field that could exist? Am I supposed to store the
    serialDescriptor
    of the enclosing class, keep track of the index of the last written element, and use that to query the descriptor to know what the field is? TL;DR: within the implementation of
    encodeInt()
    I need to find to know the current field's name, but I don't know how to.
    a
    • 2
    • 3
  • l

    Lukas K-G

    06/25/2025, 6:23 AM
    I have a strange scenario that I would need some assistance with: I have two projects that both are on Kotlin version 1.9.23 and both use kotlinx serialization plugin
    2.0.0
    . (I figured by now that this is probably a miss-configuration but haven't found any definitive documentation yet stating which plugin version to use with which Kotlin version.) Now the strange thing: One of the projects produces Kotlin metadata annotations with version
    2.0.0
    and one with
    1.9.0
    . When aligning the plugin version with the Kotlin version both produce
    1.9.0
    metadata. Can someone help me understand what might be influencing this?
  • a

    Adam S

    06/25/2025, 2:58 PM
    Why doesn't the MutableList get encoded to JSON? It only prints
    {}
    Copy code
    import kotlinx.serialization.*
    import kotlinx.serialization.json.*
    
    fun main() {
        val a = A()
        println(a)
        println(Json.encodeToString(a))
    }
    
    @Serializable
    data class A(
        val list: MutableList<String> = mutableListOf("a", "b", "c"),
    )
    Copy code
    A(list=[a, b, c])
    {}
    https://pl.kotl.in/iubN0SLUB
    ✅ 1
    e
    • 2
    • 1
  • j

    Joshua Hansen

    06/26/2025, 9:06 PM
    Facing a bit of a challenge here. The JSON serialized format of some class, we'll call it
    A
    , that my application reads has changed. I used the
    JsonNames
    annotation to account for properties that were simply renamed, but there is one property in particular whose name didn't change that went from being (in typescript speak)
    string[]
    to
    { foo: string, bar: string[] }
    . What's the best way to handle this property would could either be a list of strings or a specific class with two properties? Should I: • Create a custom serializer for this property which inspects the JSON structure of the property to determine which one it is? • Create an entire alternative class for
    A
    and use it as a surrogate after initially trying and failing to deserialize via the old format? • Some other option?
    e
    • 2
    • 3
  • s

    Scott Fedorov

    07/03/2025, 11:00 PM
    Anyone know the API for allowing a "default if type is missing for polymorphic deserialization"? Long story short, I inherited a system that has a bunch of JSON objects like
    { "a": 1, "b":2 }
    and want to start storing a new set of polydata, where it would end up serializing
    { "a": 1, "b":2, "c":2, "type": "com.example.WibbleV2" }
    ... the problem is the existing records would NOT have the type field for it to know it was V1.... trying to avoid the work of custom deserializers.
    e
    • 2
    • 2
  • e

    Eugen Martynov

    07/09/2025, 6:04 AM
    Can I have multiple constructors with kotlin serialisation? Sounds complicated and looks like I have to write a serializer by hand. Just wonder.
  • 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?