https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
serialization
  • e

    eygraber

    02/19/2021, 1:33 AM
    Is there any way to declare that a parameter to a function needs to be a type that is Serializable? For example:
    fun persist(foo: ???) {
      Json.encodeToString(foo)
    }
    e
    j
    • 3
    • 13
  • m

    melatonina

    02/19/2021, 12:11 PM
    Hello. I have number of classes which represent UUIDs for different things, like the following:
    class ProjectId(value: UUID) : Id(value) {
        companion object {
            fun new() = ProjectId(newValue())
        }
    }
    where
    Id
    is
    @Serializable
    abstract class Id(
        @Serializable(with = UUIDSerializer::class)
        val value: UUID
    ) {
        companion object {
            fun newValue(): UUID = UUID.randomUUID()
        }
        override fun hashCode(): Int = value.hashCode()
        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (other !is Id) return false
    
            if (!this.javaClass.isAssignableFrom(other.javaClass))
                return false
    
            return (value == other.value)
        }
    
        override fun toString(): String = "${javaClass.simpleName}($value)"
    }
    Is there a way to make all these
    Id
    subclasses serializable without writing the serializers by hand? Obviously, I'd like the various
    Id
    subclasses to be
    inline
    classes, but they would not be serializable at all.
    • 1
    • 1
  • a

    Ali Albaali

    02/19/2021, 9:13 PM
    Is there a way I can parse a Json list with two different models? For example a list that contains a list of posts and a list of comments? Something like this:
    """
               [
                    {
                        // Posts
                    },
                    {
                        // Comments
                    }
               ]
            """
    d
    k
    • 3
    • 7
  • m

    melatonina

    02/22/2021, 11:20 AM
    How do people typically preserve object references without duplication using kotlinx.serialization?
    o
    • 2
    • 2
  • t

    thana

    02/23/2021, 1:28 PM
    Hi, We have a
    @Serializable sealed class SuperType
    . Now we decided to add a method to all subtypes that basically create a copy from themselfs. Obvispously they are supposed to return their own type. Hence e cahnged the declaration to
    @Serializable sealed class SuperType<T: SuperType<T>>
    we can decalre the subtypes like
    class SubType: SuperType<SubType>{  override fun createCopy(): SubType = TODO()  }
    Unfortunately this seem to create a endless recursion in the compiler plugin generating the serializer for it. is this a known bug? is it a bug at all?
    c
    • 2
    • 2
  • n

    nullium21

    02/23/2021, 4:57 PM
    hi, how can I choose a type based on a string parameter, for example I have such object for type A:
    {
      "type": "A",
      "field": "foo"
    }
    and such for type B:
    {
      "type": "B",
      "foo": "bar"
    }
    how to differentiate
    @Serializable
    classes based on the
    type
    field? the classes I currently have are as follows:
    @Serializable
    sealed class Message {
        @Serializable data class A(field: String, type: String): Message()
        @Serializable data class B(foo: String, type: String): Message()
    }
    d
    • 2
    • 5
  • r

    rocketraman

    02/25/2021, 2:01 PM
    In older versions (like 0.20.0), you could create json like this:
    json {
      "foo" to "bar",
      "baz" to json {
        "gaz" to "gar"
      }
    }
    Now it seems its a lot more verbose, with calls to
    put
    . Was that intentional, or am I missing something?
    d
    p
    • 3
    • 5
  • k

    Kuba Petržílka

    02/25/2021, 2:52 PM
    Hi, I've got a question: If I create a custom serializer, how do I get the name of the field being deserialized ($FIELD_NAME)?
    override fun deserialize(decoder: Decoder): NonEmptyString {
            val decodedValue = decoder.decodeString()
            when (val result = NonEmptyString.of(decodedValue)) {
                is Success -> return result.value
                is Failure -> throw SerializationException(
                    "Unable to deserialize '$decodedValue' of $FIELD_NAME into ${descriptor.serialName}: ${result.error.message}"
                )
            }
        }
    I need to see the context in the exception because there are many feilds of type NonEmptyString in the json document being deserialized
    d
    c
    • 3
    • 6
  • d

    Dariusz Kuc

    02/26/2021, 5:50 AM
    hello 👋 by any chance is there a way to set some serializer defaults (like
    encodeDefaults = true
    etc) globally?
    d
    • 2
    • 1
  • s

    sindrenm

    02/26/2021, 3:19 PM
    After https://github.com/Kotlin/kotlinx.serialization/pull/880, what is the correct way to catch `MissingFieldException`s? Because it's now internal, doesn't have a public ancestor, and it's actually thrown when deserialization fails because of a missing field, I don't see a way (other than catching
    Exception
    and parsing the message, which I'd rather not) to catch this error.
    v
    • 2
    • 3
  • m

    melatonina

    02/26/2021, 7:42 PM
    Hello. The polymorphic serialization of a sealed class is generating this kind of json:
    ["folder",{"clipFolderId":{"value":"ae5cab51-4336-494f-86c8-e233cebc5467"}}]
    instead of something like:
    {type:"folder", "clipFolderId":{"value":"ae5cab51-4336-494f-86c8-e233cebc5467"}}
    as is described in the documentation. I'm using
    org.jetbrains.kotlin:kotlin-serialization:1.4.31
    and
    org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0
    . What could be the cause?
    d
    • 2
    • 3
  • d

    Dariusz Kuc

    02/28/2021, 2:06 AM
    hello 👋 any idea why
    kotlinx-serialization
    wraps some json elements in
    "
    making them strings?, i.e. given generic
    KSerializer
    object AnyKSerializer : KSerializer<Any> {
        override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Any")
       ...
        override fun deserialize(decoder: Decoder): Any {
            val jsonDecoder = decoder as JsonDecoder
            val element = jsonDecoder.decodeJsonElement() // why primitives are always strings?
    
            return deserializeJsonElement(element)
        }
    
        private fun deserializeJsonElement(element: JsonElement): Any = when (element) {
            is JsonObject -> {
                element.mapValues { deserializeJsonElement(it.value) }
            }
            is JsonArray -> {
                element.map { deserializeJsonElement(it) }
            }
            is JsonPrimitive -> element.content
        }
    }
    and a simple data class
    @Serializable
    data class AnyMap(
        val data: Map<String, @Serializable(with = AnyKSerializer::class) Any>
    )
    trying to deserialize
    {
      "data": {
        "intVal": 123
      }
    }
    but
    jsonDecoder.decodeJsonElement()
    converts 123 int to "123" string any ideas?
    r
    • 2
    • 4
  • v

    Victor Ermolaev

    03/02/2021, 8:25 AM
    Does anyone know exactly the place in the kotlinx.serialization source code where plugin generated serializators are generated? or, in other words, where are annotations
    @Serializable
    processed?
    a
    p
    • 3
    • 7
  • m

    Matthew Cachia

    03/02/2021, 4:45 PM
    Hi, I'm trying to deserialize a generic type
    Either<L, R>
    (which means it contains either
    L
    or
    R
    ) with the following logic:
    override fun deserialize(decoder: Decoder): Either<L, R> =
            try {
                rightSerializer.deserialize(decoder).right()
            } catch (e: Exception) {
                leftSerializer.deserialize(decoder).left()
            }
    • If the given JSON payload is meant for type
    R
    , everything works well. • If the given JSON payload is meant for type
    L
    , the exception is caught, however the cursor in the decoder has already progressed (and thus fails to deserialize) Is there a way to reset the decoder back to its original cursor position? Am I approaching this the wrong way? Are there alternatives? Thank you in advance.
    e
    j
    • 3
    • 11
  • c

    crumpf

    03/02/2021, 8:24 PM
    I’ve been battling modeling serializable classes with optionals and defaults. I understand that default property values don’t get encoded by default. I also know that one can enable
    encodeDefaults
    in the Json serialization class so defaults do get encoded. But, this has the side effect of encoding
    null
    into the json for properties that have been given default null values which is not desirable for communicating with some backend systems. So, I was wondering others have settled on for conventions or patterns to deal with this kind of thing. For example, lets considering the following example:
    interface MyInterface {
        val instruction: String
        val requiredField: String
    }
    
    @Serializable
    data class MyDataClass(
        override val requiredField: String,
        val optionalField: String? = null
    ) : MyInterface {
        override val instruction: String = "doABarrelRoll"
    }
    Here, we’ve got MyInterface which describes the basic contract that all messages exchanged with a service should adopt. To see what the effects of
    encodeDefault
    being true/false, the following code
    val data = MyDataClass("foo")
    println(Json.encodeToString(data))
    println(Json { encodeDefaults = true }.encodeToString(data))
    would output:
    {"requiredField":"foo"}
    {"requiredField":"foo","optionalField":null,"instruction":"doABarrelRoll"}
    But, we desire:
    {
      "requiredField": "foo",
      "instruction": "doABarrelRoll"
    }
    I know that a custom Serializer can be written for MyDataClass which could ignore encoding null values for properties. But, this seems that it would need to be done for all classes that incorporate optional properties. Apart from custom Serializers, has anyone used other strategies or structures for being able to encode defaults while ignoring nulls?
    p
    • 2
    • 3
  • g

    gsala

    03/03/2021, 1:07 PM
    I'm running into some issues with generic or polymorphic types:
    @Serializable
    data class Folder(
        val content: SingleOrCollection<File>
    )
    
    @Serializable
    data class File(val name: String)
    
    @Serializable
    sealed class SingleOrCollection<T> {
    
        @Serializable
        @SerialName("single")
        class Single<T>(val data: T) : SingleOrCollection<T>()
    
        @Serializable
        @SerialName("collection")
        class Collection<T>(val data: List<T>) : SingleOrCollection<T>()
    
    }
    I get a an exception when trying to serialize 
    Folder(SingleOrCollection.Single(File(fileName)))
    with
    json.encodeToString(folder)
    kotlinx.serialization.SerializationException: Class 'File' is not registered for polymorphic serialization in the scope of 'Any'.
    Mark the base class as 'sealed' or register the serializer explicitly.
    It seems looks like a pretty simple use case. Does anyone know what the issue could be?
    p
    • 2
    • 5
  • m

    Matthew Cachia

    03/04/2021, 7:46 AM
    @Serializable
    data class Request(
        @Serializable(with = EitherSerializer::class)
        val personOrCar: Either<Person, Car>,
        @Serializable(with = EitherSerializer::class)
        val catOrDog: Either<Cat, Dog>
    )
    I can easily specify my custom serializer to this sealed, third-party
    Either
    class. However,
    @Serializable
    data class Request(
        //@Serializable(???)
        val map: Map<String, Either<Cat, Dog>>
    )
    Besides some other ideas†, Is there a way I can specify a serializer for my entry value? --- † one idea is to use a custom type to replace
    Map
    and define its own custom serializer. But this is definitely not ideal.
    d
    • 2
    • 3
  • n

    Nikolay Kasyanov

    03/11/2021, 8:58 AM
    hey folks, is anyone experiencing else
    e: Compilation failed: Unbound symbols not allowed
    with K/N after bumping
    kotlinx.serialization
    to 1.1.0? Kotlin 1.4.31 is used,
    kotlinx.serialization
    1.0.1 works fine.
    • 1
    • 4
  • c

    chao

    03/15/2021, 12:18 AM
    Hello friends, does anyone know a good tool that will convert JSON Schema to Kotlinx-serialization annotated kotlin class, and preserves the property order even if JSON schema does not require any order? • https://github.com/wuseal/JsonToKotlinClass - I tried by it is crashing for my JSON schema • https://quicktype.io/ This does allow unstandard propertyOrder based on https://github.com/quicktype/quicktype/issues/336, but requires changing the JSON schema.
    c
    • 2
    • 2
  • b

    bjonnh

    03/18/2021, 7:52 PM
    I'm sure this has been asked 20 times, but how can I serialize something like :
    data class Vega(
        val background: StringOrMoreComplex
    )
    e
    • 2
    • 69
  • v

    v79

    03/21/2021, 5:41 PM
    How do I add kotlinx serialization to a subproject? I think I need to add it to build.gradle.kts
    subprojects { apply { plugin(...) } }
    but that certainly doesn't work. I don't even know what the plugin ID is. NOTE: nothing to do with multiplatform/mobile/iOS; this is a libGDX game project.
    e
    • 2
    • 2
  • c

    crummy

    03/22/2021, 6:47 AM
    Tutorials refer to
    org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:$serialization_version
    . But they seem to be using an older $serialization_version as me - I've got 1.1.0 but get "Could not find org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:1.1.0". Has this been replaced with another library or am I missing a repo?
    e
    • 2
    • 4
  • k

    Karlo Lozovina

    03/23/2021, 3:51 PM
    I often have to deserialize objects with fields that are possibly null, for example lots of them are
    Boolean?
    , and if the field is null, that's equivalent to it being
    false
    . Is there a way to get rid of nulls, and encode them as the field being false?
    j
    • 2
    • 6
  • d

    Dariusz Kuc

    03/24/2021, 2:47 AM
    hello 👋 it appears that
    ListSerializer
    only accepts a single serializer - any idea whether it is possible to specify list of different serializers to be used?
    • 1
    • 2
  • j

    Jonathan Olsson

    03/29/2021, 1:07 PM
    Hi! I was wondering if there is any community initiative for encoding/decoding commonly used jdk classes such as BigDecimal and Date with kotlinx.serialization? Browsing the internet it seems as if this is not the case but that rather people are writing their own serializers. Is this by design or further down the priority list? (Jackson by comparison has `jackson-module-kotlin`to support kotlin classes). Thanks!
    d
    p
    b
    • 4
    • 8
  • v

    Vikas Singh

    03/29/2021, 7:47 PM
    I am trying to use @SerialName but is not working any idea about this ??
    d
    r
    • 3
    • 5
  • a

    adk

    04/01/2021, 2:04 PM
    is there a kotlinx-serialization feature for automatically converting between the idiomatic camelCase property names of my kotlin classes and snake_case json field names used in the api I'm consuming? Or am I stuck with annotating every field?
    p
    • 2
    • 3
  • p

    pambrose

    04/01/2021, 5:59 PM
    I am using the newest release of IJ, the newest Kotlin plugin and Kotlin 1.4.32. I have a trivial inlined class that is annotated with @Serializable. The code builds and runs fine, but IJ gives me this warning: "Inline classes are not supported by kotlinx.serialization yet" I would greatly appreciate someone telling me how to get rid of the bogus warning in IJ. I did not have this issue prior to upgrading IJ.
    j
    • 2
    • 3
  • r

    rkeazor

    04/03/2021, 3:19 PM
    It seems that KotlinX serialization doesn't work well when it comes to obfuscation. Has anyone found a resolve to that?
    t
    l
    • 3
    • 10
  • m

    marzelwidmer

    04/04/2021, 1:32 PM
    Shame on me.. I try to parse a
    JSONN
    Array
    directly in my
    KMM
    setup with `ktor`and
    KotlinxSerializer
    and I don’t know how to define the
    Data
    class 😞
    Exception
    kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 1: Expected '{, kind: CLASS'
        JSON input: ["Albania","Argentina","Austral.....
            at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
            at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:32)
    Respnse
    [
        "Albania",
        "Argentina",
        "Australia",
    ...
    ]
    Data class
    @Serializable
    data class CountryDto(
        val names: ArrayList<String>?
    )
    API Call
    suspend fun fetchAll() = client.get<List<CountryDto>>(baseUrl)
    j
    • 2
    • 3
Powered by Linen
Title
m

marzelwidmer

04/04/2021, 1:32 PM
Shame on me.. I try to parse a
JSONN
Array
directly in my
KMM
setup with `ktor`and
KotlinxSerializer
and I don’t know how to define the
Data
class 😞
Exception
kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 1: Expected '{, kind: CLASS'
    JSON input: ["Albania","Argentina","Austral.....
        at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
        at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:32)
Respnse
[
    "Albania",
    "Argentina",
    "Australia",
...
]
Data class
@Serializable
data class CountryDto(
    val names: ArrayList<String>?
)
API Call
suspend fun fetchAll() = client.get<List<CountryDto>>(baseUrl)
j

Javier

04/04/2021, 1:35 PM
You are defining a list of lists, when you have a single list of strings
get<List<String>>
😎 1
🙏 1
m

marzelwidmer

04/04/2021, 1:38 PM
OMG
and I was trying to fix it on my data class 🙂 it works …
muchos gracias
🙂 1
View count: 14