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

    dawidhyzy

    02/26/2025, 3:01 PM
    I managed to hide it by ignoring a lint rule:
    Copy code
    <lint>
        <issue id="UnsafeOptInUsageError" severity="ignore">
            <option name="opt-in" value="kotlinx.serialization.InternalSerializationApi" />
        </issue>
    </lint>
    👀 1
  • r

    Robert Jaros

    03/02/2025, 7:24 PM
    What could this mean?
    Copy code
    throwLinkageError("Function 'encodeToString' can not be called: No function found for symbol 'kotlinx.serialization.json/Json.encodeToString|encodeToString(0:0){0\xA7<kotlin.Any?>}[0]'");
    I'm getting this when upgrading a Kotlin/JS project to Kotlin 2.1.20-RC.
    a
    s
    • 3
    • 17
  • j

    James

    03/05/2025, 12:46 PM
    I have a problem where I have this Health data class that has a generic type parameter.
    T
    can either be
    Nothing
    or something user-defined (that also has a
    @Serializable
    annotation). Whenever I try to serialize it I get an error:
    Copy code
    kotlinx.serialization.SerializationException: Serializer for class 'Health' is not found.
    Please ensure that class is marked as '@Serializable' and that the serialization compiler plugin is applied.
    All my data classes are defined with Serializable, so I'm unsure of how to go forward with this. I was thinking about writing a custom serializer that implements KSerializer. But I'm not entirely sure where to start as I haven't really looked into writing serializers before. I want to avoid doing anything JSON specific, as the type should work for other formats than JSON as well. Any advice appreciated.
    Health.kt
  • m

    Mehmet

    03/07/2025, 9:11 AM
    Is it possible to globally override the built-in serializer for a primitive type, such as
    Boolean
    , without requiring explicit
    @Contextual
    annotations on every field?
    e
    r
    • 3
    • 7
  • c

    Charann

    03/10/2025, 5:26 AM
    In the below case, I expected the serializer to de-code the scientific notation and consider it is as a "long"
    Copy code
    fun testSerializer(){
        val str = """{"doubleVal":1.725255546765E12}"""
        val json = Json {
            isLenient = true
        }
        val obj = json.decodeFromString<DoubleVal>(str)
        println(obj)
    }
    @Serializable
    class DoubleVal(val doubleVal: Long)
    But I got an error "Unexpected JSON token at offset 13: Unexpected symbol '.' in numeric literal at path: $.doubleVal" I tried using flags like "isLenient" but of no use. Am I missing any flags?
    a
    • 2
    • 1
  • k

    krzysztof

    03/13/2025, 9:16 AM
    I’m using kotlin 2.1.0, with json serialization version 1.8.0. For my data class using Uuid, the compiler gradle plugin says
    serializer has not been found for type 'Uuid'
    , but there is one built-in from serialization lib itself - how to properly mark Uuid as serializable?
    h
    • 2
    • 1
  • j

    J

    03/18/2025, 8:01 AM
    I've been trying to write a "SafeSerializer", a custom serializer that allows me to return null when the serialization of an object fails, however I feel my knowledge of serialization is lacking and I can't seem to get it to work. Has anyone done something similar, or has any idea how it would look?
    e
    • 2
    • 4
  • z

    Zyle Moore

    04/01/2025, 12:19 AM
    I have a
    @SerialInfo
    annotation that indicates that the property is tagged with the given name,
    @Field("HEDR")
    . When a property has this annotation, it is encoded as a Type-Length-Value structure. As an example,
    Copy code
    @Field("HEDR")
    val header: String = "asdf"
    Results in bytes matching
    TT TT TT TT LL LL VV VV VV VV
    (
    HEDR 04 00 asdf
    ) But, to get this to happen, I have to override the
    decode*Element
    method for each primitive, to support each serializable type. Example,
    Copy code
    @Field("HEDR")
    val header: String = "asdf"
    
    @Field("INTV")
    val taggedValues: Int = 1
    Is there an easy/cheap way to perform this tagging on any type, without overriding that specific type in the codec?
    • 1
    • 1
  • c

    CLOVIS

    04/03/2025, 11:41 AM
    I have some multiplatform code that generates JSON. However, sometimes, the JSON is slightly different in ways that doesn't matter (e.g. one system writes
    1
    and another writes
    1.0
    ). Could KotlinX.Serialization be used to deserialize multiple JSON representations and tell me if they are equal or not?
    e
    s
    • 3
    • 4
  • h

    hellman

    04/04/2025, 7:10 AM
    Hi! I have a data class with a couple of properties that should be marked
    @Transient
    and they are calculated in the init block, but that doesn't seem to be allowed. It works if I change it to a
    lateinit var
    but that seems wrong. Is this a bug in kotlinx-serialization or is there a workaround?
    c
    h
    +2
    • 5
    • 17
  • s

    Smoothie

    04/07/2025, 1:50 PM
    Hey as duplicate of #C3SGXARS6 question When I try to pass a (kotlinx serializer) JsonObject to a Kotlin listener that is used in a Swift app, that contain a JsonArray I get the error "Could not cast value of type `KListAsNSArray' to "Kotlinx_serialization_jsonJsonElement', there seem to be an issue in interop of kotlinx.serializer ? Anyone else can reproduce this issue ?
  • l

    Lukasz Kalnik

    04/07/2025, 2:55 PM
    I have to deserialize JSON, where a field can be any JSON primitive (e.g. null, int, string, double, boolean). Can I just define it in my data model as
    JsonPrimitive
    and it will work out-of-the-box?
    Copy code
    @Serializable
    data class Response(
        val field: JsonPrimitive
    )
    h
    t
    • 3
    • 19
  • e

    Emil Kantis

    04/08/2025, 9:43 AM
    Using JSON, is there any way to deserialize only keys of an object into a list? i.e
    Copy code
    {
      "foo": { // irrelevant },
      "bar": { // irrelevant },
    } -> // [ "foo", "bar ]
    Currently I got a
    Copy code
    data class Wrapper(
      val entries: Map<String, Irrelevant>
    )
    But I would like to discard/ignore the values of the map
    n
    e
    • 3
    • 14
  • 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
    • 2
    • 4
  • 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