https://kotlinlang.org logo
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
  • r

    rocketraman

    02/10/2022, 2:37 PM
    Is it possible to create an interface which requires one of its properties to be
    @Serializable
    ? Or
    @Contextual
    ? Ideally it would be a compile-time exception if the contract wasn't followed, but not the end of the world if its a runtime problem.
    d
    e
    p
    • 4
    • 5
  • r

    rtsketo

    02/10/2022, 8:11 PM
    I'm trying to find a way to make a case-insensitive deserialization, is it possible? I didn't manage to find anything in the documention about json configuration.
    r
    • 2
    • 3
  • a

    Ayfri

    02/11/2022, 3:32 PM
    Hi, is there a way to completely deactivate polymorphic serialization and just say to the library to serialize whatever there is inside because I don't need any deserialization later ?
    d
    • 2
    • 8
  • j

    John O'Reilly

    02/12/2022, 10:44 AM
    Anyone aware of way to create custom deserialization of some "map type" json in to a list (more in thread)....
    d
    e
    p
    • 4
    • 33
  • l

    louiscad

    02/16/2022, 9:05 AM
    Hello, why do you think kotlinx.serialization protobuf is still experimental? Can we expect major breaking changes in the not too distant future?
    ➕ 1
    p
    • 2
    • 4
  • a

    Amaan

    02/16/2022, 8:35 PM
    I'm trying to compile with generic classes like in the documentation, but I can't seem to get it to work. https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#generic-classes
    o
    • 2
    • 5
  • k

    kierans777

    02/21/2022, 12:03 PM
    I feel like I'm missing something obvious when trying to deserialise some JSON into an enum. Due to some developers not reading the spec properly, the server returns some JSON that is keyed incorrecty, and is lowercase.
    {
      "healthCheck": "success"
    }
    I need to parse it into an object of
    HealthCheck
    @Serializable
    data class HealthCheck(
      @SerialName("healthCheck")
      @Serializable(with = StatusSerializer::class)
      val result: Status
    ) {
      @Serializable
      enum class Status {
        SUCCESS
      }
    }
    
    object StatusSerializer : JsonTransformingSerializer<HealthCheck.Status>(HealthCheck.Status.serializer()) {
      override fun transformDeserialize(element: JsonElement): JsonElement {
        val el = super.transformDeserialize(element)
    
        return JsonPrimitive(el.toString().uppercase())
      }
    }
    However I get an exception
    HealthCheck.Status does not contain element with name '"SUCCESS"'
    e
    • 2
    • 6
  • r

    rrva

    02/22/2022, 5:49 PM
    Is there any code generation from XSD schema available?
    b
    • 2
    • 1
  • a

    Amaan

    02/23/2022, 4:05 PM
    I'm trying to make an Event publisher that can take any serializable type as a payload and send it off to the event endpoint that we have, but I'm not sure how to do that without the failure
    java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
    . Here is my attached code, but essentially I want a single function that can publish all my events and every time I want to create a new type of event, I can just create a class that extends it with the right payload type.
    n
    • 2
    • 27
  • j

    Justin Breitfeller

    02/23/2022, 7:43 PM
    I have a class that sometimes I need to merge into another class when serializing. Is it possible to add a descriptor to another descriptor? Essentially merging the elements together?
    d
    • 2
    • 3
  • o

    Olli Helenius

    02/25/2022, 11:27 AM
    is there some way to require that a type is serializable, something like
    class Container<@Serializable T> …
    ?
    d
    • 2
    • 2
  • g

    George

    02/25/2022, 3:34 PM
    Hey guys, is the plugin code open-sourced?
    m
    • 2
    • 2
  • d

    Dariusz Kuc

    03/01/2022, 12:32 AM
    Hello 👋 Is there a way to coerce default polymorphic type programmatically? i.e. something like https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#default-polymorphic-type-handler-for-deserialization but by using only annotations Guess I can provide default value together with
    Json {
        coerceInputValues = true
    }
    • 1
    • 3
  • m

    mkrussel

    03/02/2022, 3:08 PM
    Is it expected that the first deserialization from a
    Json
    instance will be slow? Parsing a small JSON text in some unit tests. The first test takes 167 ms (longer on build machine) just in the parsing. All the other tests take about one millisecond to parse the same amount of JSON. This is on the JVM with Kotlin 1.6.10 and Serialization 1.3.2.
    b
    e
    m
    • 4
    • 5
  • a

    Anton Afanasev

    03/02/2022, 6:08 PM
    I have a KMM library that use kotlinx.serialization for serialization. Some Android application has a dependency to my library and it has an issue with proguard. This app has
    minifyEnabled = true
    and therefore some of my data classes are removed by proguard. I was able to resolve that by adding a proguard rule to keep this classes, but it did work only when I apply this rule on the app side. Wonder if it is even possible to have this rules on the library side so that app would not need to modify their proguard rules
    m
    e
    • 3
    • 5
  • s

    SrSouza

    03/03/2022, 3:55 PM
    Hi folks, there is any annotation that can be used to tell that a type must be a
    @Serializable
    one? For Java we can easily use Serializable and on Android also Parcelable.
    🇳🇴 2
    c
    p
    • 3
    • 3
  • e

    Emerson Farrugia

    03/03/2022, 5:14 PM
    Hi 👋 Background: I've got a service, let's call it Service 1, that offers a RESTful API endpoint and uses Jackson for deserialization. Service 1 makes API calls to Service 2. To make these calls, Service 1 uses a Service 2 client SDK which is written in Kotlin, defines Kotlin DTOs, and uses Kotlin Serialization. The SDK isn't just written in Kotlin, it's actually auto-generated from an OpenAPI spec, so I can't easily change the SDK's code. Question: Some of the data Service 1 receives has to be passed verbatim to Service 2. I'm trying to avoid rewriting DTOs for all this data, since they're sitting right there in the SDK with Kotlin Serialization annotations. Is there some way for Service 1 to use Jackson to deserialize into those Kotin Serialization DTOs, e.g. treating
    @SerialName
    as
    @JsonProperty
    for these simple DTOs.
    c
    • 2
    • 1
  • i

    Ian

    03/07/2022, 3:08 AM
    Hi, I'm getting this error when I run some Kotlin code on Elastic Beanstalk that I'm not getting when I run locally, it appears to be an exception within
    KClasses.getMemberProperties()
    . I'm using Kotlin 1.6.10 - would appreciate any suggestions:
    java.lang.ClassCastException: class kotlin.jvm.internal.ClassReference cannot be cast to class kotlin.reflect.jvm.internal.KClassImpl (kotlin.jvm.internal.ClassReference and kotlin.reflect.jvm.internal.KClassImpl are in unnamed module of loader 'app')
     at kotlin.reflect.full.KClasses.getMemberProperties(KClasses.kt:148)
    • 1
    • 2
  • g

    George

    03/09/2022, 12:13 PM
    Hi folks, when i serialize manually in json the outcome produces escaped chars:
    "data": "{\"imahubKey\":\"eyJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJpbWFodWIiLCJzdWIiOiJ0ZXN0NTIxMDEiLCJleHAiOjE2NDY4MzM2MzIsImlhdCI6MTY0NjgyMzYzMn0.5L6T1-8EkzR41IX2V43ImI1hfBrIMEJEXXTr88FD8QbST82-l4_kg31tjA0xph_LgvUGPuMtXsRhfx44WgvcAA\"}"
    This is my serializer:
    public fun SharedPayload.encodeToJson(): JsonElement = SharedPayloadJson.encodeToJsonElement(
        SharedSharedPayloadFromBuilder.serializer(), this as SharedSharedPayloadFromBuilder
    How can i disable the escaping when im dealing with strings?
    n
    • 2
    • 5
  • g

    George

    03/11/2022, 6:17 PM
    Hi folks, i have an interface
    public sealed interface SharedPayload {
        public val data: JsonElement?
        public val error: ApiError?
    }
    and an impl
    @PublishedApi
    @Serializable
    internal class SharedSharedPayloadFromBuilder : SharedPayloadBuilder, SharedPayload {
        @Transient
        private var hasData = false
    
        @Transient
        private var hasErrors = false
    
        @Polymorphic
        override var data: JsonElement? = null
            private set
    
        override var error: ApiError? = null
            private set
    
        override fun data(value: JsonElement?) {
            if (hasData) {
                error("Data already provided")
            }
            data = value
            hasData = true
        }
    
        override fun error(value: ApiError) {
            if (hasErrors) {
                error("Error already provided")
            }
            error = value
            hasErrors = true
        }
    
        fun build(): SharedPayload {
            check(hasData || hasErrors) { "Data or error is required" }
            return this
        }
    }
    Im serializing any object into data as jsonElement, then i want to serialize the whole object as a jsonElement, yet i got this err
    Serializer for JsonPrimitive of kind STRING cannot be serialized polymorphically with class discriminator.
    Anyone got any idea what im doing wrong? The test i run is this:
    @Test
    fun test() {
        val payload = buildSharedPayload {
            data(ApiRequest("Hello from api request as json element"))
        }
        println(payload.data)
        val jsonElement = payload.encodeToJson()
        println(jsonElement)
    
        val data = SharedPayload("Hello im json element")//.encodeToJson()
        println(data.data)
    }
    fyi here is a sample project with this: https://github.com/GeorgePap-719/simple-springboot-kotlinx-serialization Thanks in advance for any help!
    r
    • 2
    • 5
  • o

    Ola Gawell

    03/15/2022, 3:10 PM
    Hi! I get this error when trying to do a polymorphic deserialization of a class with generic typing. I am using a custom serializer
    KSerializer
    to handle the different subclasses. Code in thread.
    java.lang.AssertionError: No such value argument slot in IrConstructorCallImpl: 0 (total=0).
    Symbol: /IntValueProviderSerializer.<init>|-5645683436151566731[0]
    We are using a multiplatform project with
    org.jetbrains.kotlinx:kotlinx-serialization-json: 1.3.2
    a
    • 2
    • 8
  • l

    LastExceed

    03/17/2022, 9:27 AM
    i need to decode a json string with a weird quirk. lists with only 1 entry omit the
    []
    as if it was just a simple property of the inner type. eg
    x = listOf("foo", "bar")
    is serialized as
    "x": ["foo", "bar"]
    (as expected), but
    x = listOf("foo")
    is serialized as
    "x": "foo"
    instead of
    "x": ["foo"]
    . this breaks the parser, because it sees a
    x: String
    property where
    x: List<String>
    is expected. how do i work around this?
    • 1
    • 1
  • a

    andylamax

    03/18/2022, 8:24 AM
    hello there, is there a way to serialize this without using a custom serializer?
    @Serializable
    sealed class InfoResults<out T> {
        @Serializable
        data class Shared<out T>(val data: T) : InfoResults<T>()
    
        @Serializable
        data class NotShared(val message: String) : InfoResults<Nothing>()
    }
    r
    p
    r
    • 4
    • 13
  • a

    Adam S

    03/18/2022, 2:56 PM
    hi, I'm working on creating a library to generate TypeScript interfaces based on SerialDescriptors. I'm stuck on how to translate parent and sub classes though. Is it possible to get this information from SerialDescriptors, or SerializersModule? Or do I have to use kapt, or reflection, or KSP? Attached is an example of what I'd like to make
    Untitled.cpp
    e
    • 2
    • 1
  • j

    jmfayard

    03/20/2022, 3:17 PM
    Hello World, I have litteraly dozens of Enum classes like this where the default Enum serializer don't work only because the case is different, PascalCase in Kotlin versus snake_case when serialized. Is it possible to somehow wrap the default serializer to add a call to
    .toPascalCase()
    and
    .to_snake_case()
    instead of having all those
    @SerialName
    ?
    p
    e
    t
    • 4
    • 5
  • y

    Yousef

    03/21/2022, 4:33 PM
    Hello, I'm getting error
    Unexpected JSON token at offset 11023: Expected start of the object '{', but had ':' instead
    JSON input: .....","type":"BLOGPOST","category":"e054042e-bc50-4743-a6f5-94d9.....
    and I'm not sure why
    e
    r
    • 3
    • 10
  • i

    Icyrockton

    03/23/2022, 12:55 PM
    how do I implement kotlinx.serialization in spring data redis?
    n
    • 2
    • 1
  • k

    kevin.cianfarini

    03/25/2022, 8:11 PM
    How can I specify a class discriminator on an interface?
    @JsonClassDiscriminator("country")
    sealed interface Market {
    
        @Serializable @SerialName("UK")
        object UnitedKingdom : Market
    
        @Serializable @SerialName("US")
        enum class UnitedStates : Market {
            @SerialName("TX") Texas,
        }
    }
    Here the discriminator doesn’t do anything because the interface isn’t serializable (I think). I don’t want to globally specify the discriminator because it’s only applicable to this hierarchy
    d
    e
    • 3
    • 6
  • s

    SrSouza

    03/31/2022, 4:45 PM
    Hi folks, there is any solution for better error handling when using Kotlinx.serialization and Json? Currently the SerializationException don't tell much, would be awesome to see what names/types fail in the serialization.
    k
    • 2
    • 1
  • c

    Conrad Kramer

    04/01/2022, 7:19 PM
    What is the best way to deserialize a heterogenous array that looks like this in JSON? I can write a custom serializer, but I am stuck on which descriptor to use, because
    listSerialDescriptor
    assumes a homogenous array.
    [{"key": "value"}, "string"]
    In Swift, I can pull arbitrary types out of an
    UnkeyedDecodingContainer
    in any order I need
    a
    e
    • 3
    • 7
Powered by Linen
Title
c

Conrad Kramer

04/01/2022, 7:19 PM
What is the best way to deserialize a heterogenous array that looks like this in JSON? I can write a custom serializer, but I am stuck on which descriptor to use, because
listSerialDescriptor
assumes a homogenous array.
[{"key": "value"}, "string"]
In Swift, I can pull arbitrary types out of an
UnkeyedDecodingContainer
in any order I need
It seems like the best i can do is use polymorphic serialization for the entire array with a fixed set of subtypes and then runtime cast them, hoping that the object shapes are distinct enough to not be confused for one another because I cannot use the position in the array as a hint to the serializer even though I know the types ahead of time
a

ankushg

04/01/2022, 8:02 PM
You could also maybe serialize it into JsonElements and write something to manually walk the tree… It’s definitely not ideal, but it lets you do stuff like use the positions in the list in some more manual serialization logic https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#json-elements
c

Conrad Kramer

04/01/2022, 8:49 PM
I might have to do that because even Polymorphic does not work here – Polymorphic seems to assume JsonObject and not JsonElement
yeah, https://github.com/Kotlin/kotlinx.serialization/blob/920f58979990bace9aaecd300e59b[…]mmonMain/src/kotlinx/serialization/json/internal/Polymorphic.kt it requires a discriminator, too, so only supports “internal tagging” in serde.rs parlance
e

ephemient

04/01/2022, 10:04 PM
there is Json.useArrayPolymorphism but that isn't what you want either
you'll have to write a custom serializer, it doesn't have to be too hard if you use
ListSerializer(JsonElement.serializer())
(or equivalents) as a surrogate. It won't work for any format other than JSON, but this kind of structure also doesn't work with other formats so you're not really losing anything
c

Conrad Kramer

04/02/2022, 4:07 AM
Yep, totally. JsonElement ended up working pretty well!
View count: 25