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
  • a

    Akbar

    12/31/2021, 2:16 PM
    is it helpful in parsing data ?
    d
    • 2
    • 9
  • j

    Jeremiah Zucker

    01/03/2022, 8:25 PM
    Hey folks, hopefully quick question. I’ve been using Kotlinx serialization for a while and recently was trying to write a custom serializer/descriptor for a nested structure. I then realized that I wasn’t going to be able to reference the descriptor from within `buildClassSerialDescriptor`:
    class SomeSerializer : KSerializer<SomeClass> {
        override val descriptor: SerialDescriptor = buildClassSerialDescriptor("SomeClass") {
            element<Boolean>("flag")
            element("nested", SomeSerializer().descriptor, isOptional = true)
        }
        // ...
    }
    This leads to a stack overflow since the
    init
    of
    SomeSerializer
    creates the
    descriptor
    which then tries to new up another
    SomeSerializer
    . That makes sense to me, but I wasn’t sure what the intended way of accomplishing something like this is. I know it’s possible if using one of the plugin generated serializers. Does this mean I might potentially need to implement
    SerialDescriptor
    myself or is this something that’s already solved for and I’m just not seeing the path forward?
    • 1
    • 1
  • j

    Jan

    01/04/2022, 12:08 AM
    Hey I can't figure out how to serilize this in kotlin. Preferably with kotlinx serilizastion. Here a typescript reference. Can someone guide me to an implementation?
    function handleData(data: Record<string, unknown>) {
    const bar: Record<string,unknown> = {
    foo: "hi",
    props: {...this.otherData, ...data}
    }
    return bar
    }
    This should end up as
    { 
    foo: "hi",
    props: {
      uno: 1
      dos: "two"
     }
    }
    j
    • 2
    • 7
  • e

    Eugen Martynov

    01/04/2022, 11:35 AM
    Is there way to overrider json key that is responsible for the sealed class serialisation pick up?
    p
    • 2
    • 17
  • s

    sindrenm

    01/04/2022, 5:30 PM
    Is there a way to provide a default type for a list of polymorphic types on the type declaration level (e.g. something akin to how
    @JsonClassDiscriminator
    makes class discriminators more customizable)? Sample code in thread.
    d
    • 2
    • 13
  • j

    jeff

    01/04/2022, 5:36 PM
    (Edit: wrong channel, this is kotlinx.serialization not serialization in general. Apologies)
    b
    p
    e
    • 4
    • 3
  • r

    rocketraman

    01/06/2022, 7:47 PM
    I have a sealed class hierarchy, but the input JSON (externally defined) uses
    _type
    instead of
    type
    as the discriminator. Doing
    @SerialName("_type") val type: String
    doesn't seem to work. A JSON content-based polymorphic deserialization seems like overkill for this. Is there some annotations that will work short of that?
    a
    • 2
    • 3
  • a

    andylamax

    01/07/2022, 12:28 AM
    Hey there, why don't custom serializers come have the Companion.serializer() method?? I have
    @Serializable(with = SignedIn.Companion::class)
    interface SignedIn : Session {
    
        @Serializer(forClass = SignedIn::class)
        companion object : KSerializer<SignedIn> {
            override val descriptor: SerialDescriptor = buildClassSerialDescriptor("session.signedin")
    
            override fun deserialize(decoder: Decoder): SignedIn {
                TODO("Not yet implemented")
            }
    
            override fun serialize(encoder: Encoder, value: SignedIn) {
                TODO()
            }
        }
    }
    And my test are as follows
    val session : SignedIn = getSession()
    println(Json.encodeToString(session)) // fails with: Serializer for class 'SignedIn' is not found.
    println(Json.encodeToString(SignedIn,session)) // passes
    println(Json.encodeToString(SignedIn.serializer(),session)) // won't compile
    Why can't the compiler find the custom serializer??
    e
    a
    • 3
    • 7
  • j

    Jason5lee

    01/08/2022, 1:01 PM
    Can I makes a field allowing either a string or an object of a certain class? The JSON is from others so I cannot change its shape.
    d
    • 2
    • 1
  • r

    Rahul Rawat

    01/09/2022, 6:10 PM
    I have made a KMP library and am trying to use the output aar in android and the following issue is coming
    java.lang.RuntimeException: Unable to instantiate application com.rawat.address.AddressApp: java.lang.TypeNotPresentException: Type kotlinx.serialization.json.Json not present
            at android.app.LoadedApk.makeApplication(LoadedApk.java:1244)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6683)
            at android.app.ActivityThread.access$1300(ActivityThread.java:237)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913)
            at android.os.Handler.dispatchMessage(Handler.java:106)
            at android.os.Looper.loop(Looper.java:223)
            at android.app.ActivityThread.main(ActivityThread.java:7656)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
         Caused by: java.lang.TypeNotPresentException: Type kotlinx.serialization.json.Json not present
            at libcore.reflect.ParameterizedTypeImpl.getRawType(ParameterizedTypeImpl.java:69)
            at libcore.reflect.ParameterizedTypeImpl.getResolvedType(ParameterizedTypeImpl.java:77)
            at libcore.reflect.ListOfTypes.resolveTypes(ListOfTypes.java:70)
            at libcore.reflect.ListOfTypes.getResolvedTypes(ListOfTypes.java:55)
            at libcore.reflect.ParameterizedTypeImpl.getResolvedType(ParameterizedTypeImpl.java:76)
            at libcore.reflect.Types.getType(Types.java:56)
            at java.lang.Class.getGenericSuperclass(Class.java:878)
            at org.kodein.type.TypeReference.<init>(typeTokensJVM.kt:65)
            at com.library.address.di.KodeinKt$commonModule$$inlined$bindSingleton$default$1.<init>(typeTokensJVM.kt:83)
            at com.library.address.di.KodeinKt.commonModule(Kodein.kt:79)
            at com.library.address.di.KodeinKt.access$commonModule(Kodein.kt:1)
            at com.library.address.di.KodeinKt$initKodein$container$1.invoke(Kodein.kt:26)
            at com.library.address.di.KodeinKt$initKodein$container$1.invoke(Kodein.kt:23)
            at org.kodein.di.internal.DIImpl$Companion.newBuilder(DIImpl.kt:21)
            at org.kodein.di.internal.DIImpl$Companion.access$newBuilder(DIImpl.kt:20)
            at org.kodein.di.internal.DIImpl.<init>(DIImpl.kt:18)
            at org.kodein.di.DI$Companion.invoke(DI.kt:460)
            at org.kodein.di.DI$Companion.invoke$default(DI.kt:460)
            at com.library.address.di.KodeinKt.initKodein(Kodein.kt:23)
            at com.library.address.di.KodeinKt.initKodein$default(Kodein.kt:22)
            at com.rawat.address.AddressApp.<init>(AddressApp.kt:8)
            at java.lang.Class.newInstance(Native Method)
            at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76)
            at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52)
            at android.app.Instrumentation.newApplication(Instrumentation.java:1158)
            at android.app.LoadedApk.makeApplication(LoadedApk.java:1236)
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6683) 
            at android.app.ActivityThread.access$1300(ActivityThread.java:237) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) 
            at android.os.Handler.dispatchMessage(Handler.java:106) 
            at android.os.Looper.loop(Looper.java:223) 
            at android.app.ActivityThread.main(ActivityThread.java:7656) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
         Caused by: java.lang.ClassNotFoundException: kotlinx.serialization.json.Json
            at java.lang.Class.classForName(Native Method)
            at java.lang.Class.forName(Class.java:454)
            at libcore.reflect.ParameterizedTypeImpl.getRawType(ParameterizedTypeImpl.java:67)
            at libcore.reflect.ParameterizedTypeImpl.getResolvedType(ParameterizedTypeImpl.java:77) 
            at libcore.reflect.ListOfTypes.resolveTypes(ListOfTypes.java:70) 
            at libcore.reflect.ListOfTypes.getResolvedTypes(ListOfTypes.java:55) 
            at libcore.reflect.ParameterizedTypeImpl.getResolvedType(ParameterizedTypeImpl.java:76) 
            at libcore.reflect.Types.getType(Types.java:56) 
            at java.lang.Class.getGenericSuperclass(Class.java:878) 
            at org.kodein.type.TypeReference.<init>(typeTokensJVM.kt:65) 
            at com.library.address.di.KodeinKt$commonModule$$inlined$bindSingleton$default$1.<init>(typeTokensJVM.kt:83) 
            at com.library.address.di.KodeinKt.commonModule(Kodein.kt:79) 
            at com.library.address.di.KodeinKt.access$commonModule(Kodein.kt:1) 
            at com.library.address.di.KodeinKt$initKodein$container$1.invoke(Kodein.kt:26) 
            at com.library.address.di.KodeinKt$initKodein$container$1.invoke(Kodein.kt:23) 
            at org.kodein.di.internal.DIImpl$Companion.newBuilder(DIImpl.kt:21) 
            at org.kodein.di.internal.DIImpl$Companion.access$newBuilder(DIImpl.kt:20) 
            at org.kodein.di.internal.DIImpl.<init>(DIImpl.kt:18) 
            at org.kodein.di.DI$Companion.invoke(DI.kt:460) 
            at org.kodein.di.DI$Companion.invoke$default(DI.kt:460) 
            at com.library.address.di.KodeinKt.initKodein(Kodein.kt:23) 
            at com.library.address.di.KodeinKt.initKodein$default(Kodein.kt:22) 
            at com.rawat.address.AddressApp.<init>(AddressApp.kt:8) 
            at java.lang.Class.newInstance(Native Method) 
            at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76) 
            at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52) 
            at android.app.Instrumentation.newApplication(Instrumentation.java:1158) 
            at android.app.LoadedApk.makeApplication(LoadedApk.java:1236) 
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6683) 
            at android.app.ActivityThread.access$1300(ActivityThread.java:237) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) 
            at android.os.Handler.dispatchMessage(Handler.java:106) 
            at android.os.Looper.loop(Looper.java:223) 
            at android.app.ActivityThread.main(ActivityThread.java:7656) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947) 
         Caused by: java.lang.ClassNotFoundException: Didn't find class "kotlinx.serialization.json.Json" on path: DexPathList[[dex file "/data/data/com.rawat.address/code_cache/.overlay/base.apk/classes7.dex", zip file "/data/app/~~U3m2k-_-ig7S7cGbCNubiA==/com.rawat.address-AHUnIhfVwegLlNWqeSa9yQ==/base.apk"],nativeLibraryDirectories=[/data/app/~~U3m2k-_-ig7S7cGbCNubiA==/com.rawat.address-AHUnIhfVwegLlNWqeSa9yQ==/lib/x86, /system/lib, /system_ext/lib]]
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:207)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
            at java.lang.Class.classForName(Native Method) 
            at java.lang.Class.forName(Class.java:454) 
            at libcore.reflect.ParameterizedTypeImpl.getRawType(ParameterizedTypeImpl.java:67) 
            at libcore.reflect.ParameterizedTypeImpl.getResolvedType(ParameterizedTypeImpl.java:77) 
            at libcore.reflect.ListOfTypes.resolveTypes(ListOfTypes.java:70) 
            at libcore.reflect.ListOfTypes.getResolvedTypes(ListOfTypes.java:55) 
            at libcore.reflect.ParameterizedTypeImpl.getResolvedType(ParameterizedTypeImpl.java:76) 
            at libcore.reflect.Types.getType(Types.java:56) 
            at java.lang.Class.getGenericSuperclass(Class.java:878) 
            at org.kodein.type.TypeReference.<init>(typeTokensJVM.kt:65) 
            at com.library.address.di.KodeinKt$commonModule$$inlined$bindSingleton$default$1.<init>(typeTokensJVM.kt:83) 
            at com.library.address.di.KodeinKt.commonModule(Kodein.kt:79) 
            at com.library.address.di.KodeinKt.access$commonModule(Kodein.kt:1) 
            at com.library.address.di.KodeinKt$initKodein$container$1.invoke(Kodein.kt:26) 
            at com.library.address.di.KodeinKt$initKodein$container$1.invoke(Kodein.kt:23) 
            at org.kodein.di.internal.DIImpl$Companion.newBuilder(DIImpl.kt:21) 
            at org.kodein.di.internal.DIImpl$Companion.access$newBuilder(DIImpl.kt:20) 
            at org.kodein.di.internal.DIImpl.<init>(DIImpl.kt:18) 
            at org.kodein.di.DI$Companion.invoke(DI.kt:460) 
            at org.kodein.di.DI$Companion.invoke$default(DI.kt:460) 
            at com.library.address.di.KodeinKt.initKodein(Kodein.kt:23) 
            at com.library.address.di.KodeinKt.initKodein$default(Kodein.kt:22) 
            at com.rawat.address.AddressApp.<init>(AddressApp.kt:8) 
            at java.lang.Class.newInstance(Native Method) 
            at android.app.AppComponentFactory.instantiateApplication(AppComponentFactory.java:76) 
            at androidx.core.app.CoreComponentFactory.instantiateApplication(CoreComponentFactory.java:52) 
            at android.app.Instrumentation.newApplication(Instrumentation.java:1158) 
            at android.app.LoadedApk.makeApplication(LoadedApk.java:1236) 
            at android.app.ActivityThread.handleBindApplication(ActivityThread.java:6683) 
            at android.app.ActivityThread.access$1300(ActivityThread.java:237) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1913) 
            at android.os.Handler.dispatchMessage(Handler.java:106) 
            at android.os.Looper.loop(Looper.java:223) 
            at android.app.ActivityThread.main(ActivityThread.java:7656) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
    Can anyone help?
    :thread-please: 1
    j
    • 2
    • 5
  • a

    andylamax

    01/10/2022, 12:25 PM
    Hey there, This might not be specific to serialization but I will ask here coz of obvious reasons. I am currently getting this error
    > Task compileKotlinJs FAILED
    e: Could not find "org.jetbrains.kotlinx:kotlinx-serialization-core" in [/home/andylamax/.local/share/kotlin/daemon]
    e: java.lang.IllegalStateException: Could not find "org.jetbrains.kotlinx:kotlinx-serialization-core" in [/home/andylamax/.local/share/kotlin/daemon]
    It should be known that this is a multiplatform project and task compileKotlinJvm completes successfully. Anyone experienced this?? how do I solve it?? Full error log in thread
    • 1
    • 1
  • f

    Florian Magin

    01/11/2022, 3:07 PM
    Conceptual Question: I want to deserialize a JsonPrimitive (e.g. an integer) into specific class that is not an Integer because in the context of my code it is more than simply an Integer (e.g. a user ID that can be mapped to a User object using some DB). Is there some elegant way to do this with kotlinx.serialization? Because this requires more external information, this would probably need me to specify the mapping from
    Integer -> User
    when I instantiate the JSON deserializer. Is there such a functionality already available?
    d
    • 2
    • 21
  • e

    Eugen Martynov

    01/13/2022, 4:21 PM
    How can I achieve something like
    @Serializable
    @Contextual
    abstract class BaseCreateProfileData {...}
    d
    • 2
    • 9
  • n

    Nikky

    01/14/2022, 11:38 AM
    i have a test in which i feed
    "{"type": "A", ...}"
    into a
    PolymorphicType.A.serializer()
    it fails with a
    Unexpected JSON token at offset 11: Encountered an unknown key 'type'.
    is there a way to skip that.. while also not adding
    type
    as a property to the class (because that creates other issue) or using
    ignoreUnknownKeys = true
    because there could be other.. issues ? oone way i found was to use
    val a = Json.decodeFromString(PolymorphicType.serializer(), jsonString) as PolymorphicType.A
    but that means that there is no way to use this.. except for encoding and decoding using the polymorphic types.. or you wil lose the
    type
    properties
    e
    d
    • 3
    • 8
  • e

    Eugen Martynov

    01/14/2022, 3:42 PM
    Can I use
    JsonTransformingSerializer
    to remove discriminator?
    d
    • 2
    • 6
  • s

    spierce7

    01/15/2022, 4:13 AM
    Why does Kotlinx Serialization protobufs target proto 2, not proto 3?
    e
    j
    +2
    • 5
    • 27
  • r

    rocketraman

    01/19/2022, 3:57 PM
    Does anyone have a workaround to https://github.com/Kotlin/kotlinx.serialization/issues/944 ?
    p
    • 2
    • 3
  • a

    andrew

    01/19/2022, 6:36 PM
    Is there any way to utilize classDiscriminator on a specific key when deserializing an abstract class, but without using the qualified name as a value, but a custom value?
    d
    n
    • 3
    • 16
  • v

    v79

    01/25/2022, 9:17 PM
    Can anyone help me make sense of this serialization & javascript compiler error?
    2022-01-25T21:03:42.507+0000 [DEBUG] [org.gradle.execution.plan.Node] Checking if all dependencies are complete for :jsProductionExecutableCompileSync
    2022-01-25T21:03:42.507+0000 [DEBUG] [org.gradle.execution.plan.Node] All dependencies are complete for :jsProductionExecutableCompileSync
    2022-01-25T21:03:42.507+0000 [DEBUG] [org.gradle.execution.plan.TaskNode] Checking if all must successors are complete for :jsProductionExecutableCompileSync
    java.util.NoSuchElementException: Collection contains no element matching the predicate.
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.IrBuilderExtension$DefaultImpls.createLazyProperty(GeneratorHelpers.kt:1401)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializableCompanionIrGenerator.createLazyProperty(SerializableCompanionIrGenerator.kt:35)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializableCompanionIrGenerator.generateLazySerializerGetter(SerializableCompanionIrGenerator.kt:114)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializableCompanionCodegen.generate(SerializableCompanionCodegen.kt:37)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.ir.SerializableCompanionIrGenerator$Companion.generate(SerializableCompanionIrGenerator.kt:50)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializerClassLowering.lower(SerializationLoweringExtension.kt:60)
    ...
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1802)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    	at java.rmi/sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:359)
    	at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:200)
    	at java.rmi/sun.rmi.transport.Transport$1.run(Transport.java:197)
    	at java.base/java.security.AccessController.doPrivileged(Native Method)
    	at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:562)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:796)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:677)
    	at java.base/java.security.AccessController.doPrivileged(Native Method)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:676)
    	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    	at java.base/java.lang.Thread.run(Thread.java:834)
    I have code which runs and compiles fine on the JVM, but fails when compiling to Javascript. The error logs don't tell me where in my code it's failing. If it helps, my data model to be serialized has a
    sealed
    class with a number of children, each of which implement different interfaces. None of them use
    by lazy
    .
    d
    • 2
    • 3
  • i

    iamthevoid

    01/26/2022, 3:21 PM
    Hi! I Try to parse this class from json [1] ServerErrors is enum that should be deserialized well [2] I receive body [3] and try to parse it and get error [4] I can read and see what is wrote in, but i had this flag enabled in my json plugin in client [5] What can i miss?
    🧵 1
    n
    • 2
    • 25
  • g

    George

    01/27/2022, 3:57 PM
    Hi, any known workarounds for avoiding the type in json serialization?. For deserializing i can provide a selectDeserializer. Im found this https://github.com/Kotlin/kotlinx.serialization/issues/1247 but i think it does not mention any workaround for erasing the type in serialization. My use case is pretty simple i think, i just have a sealed interface with an implementation
    d
    • 2
    • 4
  • j

    Javier

    01/30/2022, 2:16 AM
    Not sure if put this here or in Ktor I have a custom sealed class which works perfectly via local strings and ktor request if I use my custom serializer
    @Serializable(with = CustomSealedClassSerializer::class)
    . But I want to remove the dependency on
    json
    this sealed class in that Gradle module so I tried to use a
    SerializerModule
    Json {
        serializersModule = SerializersModule {
            contextual(CustomSealedClassSerializer::class) { args -> CustomSealedClassSerializer(args[0], args[1] }
        }
        ...
    }
    This is working perfectly with local strings, but with Ktor
    2.0.0-alpha-1
    and doing a request, it is not working, and debugging I am getting that
    args
    list is empty. Is there any workaround?
    d
    a
    • 3
    • 7
  • g

    Guilherme Delgado

    01/31/2022, 5:47 PM
    Hello! I’m trying to manually parse a
    Map<String, String>
    json response from github’s API into a
    List<Object>
    but I’m failing to do so, more in the thread
    d
    p
    • 3
    • 15
  • d

    dave08

    02/02/2022, 12:36 PM
    What does kotlin serialization do with
    {"a": "a", "b":true, "c":1, "d": 10000000000000000000}
    (if I want it as
    Map<String, Any>
    ), and would it differentiate between
    Int
    Long
    Float
    and
    Double
    ? Or does it just put all numbers in one of those (In Moshi, they just put them all in Doubles... https://github.com/square/moshi/issues/1144)? Do I need to manually serialize all this or is there an easy way to do this?
    d
    j
    • 3
    • 23
  • k

    Kuba Petržílka

    02/02/2022, 3:04 PM
    Hello, how can I configure the following:
    sealed interface SystemXsId {
        @Serializable
        @JvmInline
        value class Known(val value: NonEmptyString) : SystemXsId
    
        @Serializable
        object Unknown : SystemXsId
    }
    to be serialized either as: • the value of NonEmptyString (which is already serializable and it works) - in case it is
    Known
    • null in case it is
    Unknown
    I probably have to specify an explicit serializer for the sealed interface, but how would it look like?
    d
    • 2
    • 1
  • r

    Rohan Maity

    02/03/2022, 4:05 PM
    does kotlin serialziation uses
    Serializable
    of java ? why I am asking this question, actually we need to store the some serialized data in local/Room DB With Java's Serializable, problem is if we make any changes to the class implementing Serializable,. Its
    serialVersionUID
    gets changed, which causes the problem in deserializing
    c
    • 2
    • 5
  • l

    Lost Illusion

    02/05/2022, 11:04 PM
    Hello, I'm working with a protocol that serializes fields as the indices of an array. For example
    {
      "type": 1,
      "realm": "dev"
    }
    would actually be serialized as
    [1, "dev"]
    and I'm not too sure how to go about this. I was going to go with a message hierarchy and then delegate to the specific serializer based off the type, which I've successfully done before with the first JSON example. Though, I'm not sure how to do that with the second example, nor how to even (de)serialize the second example into a class that would look like this.
    data class Foo(val type: Int, val realm: String)
    It'd be nice to know if this is even possible, since I'm completely stumped on how to create a proper descriptor for the second situation. Thanks.
    • 1
    • 1
  • d

    Dariusz Kuc

    02/06/2022, 8:39 PM
    Hello 👋 Wondering if anyone tried using https://github.com/tschuchortdev/kotlin-compile-testing together with
    kotlinx-serialization
    ? I'm trying to test out my auto-generated code but since serialization build plugin wasn't run, my compilation is failing as the serialization generated code is not available (e.g.
    <foo>.serializer()
    on serializable objects). Any ideas/suggestions?
    e
    • 2
    • 7
  • a

    Ayfri

    02/06/2022, 9:54 PM
    Hi, is there a way to modify how an enum value will serialize ? I have this enum :
    @Serializable
    enum class Environment {
    	BOTH,
    	CLIENT,
    	SERVER;
    }
    And I want the
    BOTH
    value to be serialized to
    *
    e
    • 2
    • 2
  • a

    alightgoesout

    02/09/2022, 1:00 PM
    I have a generic class
    Id<T>
    where
    T
    is not actually used for serialization/deserialization. I have written a custom serializer for it that I have declared on the class (
    @Serializable(with = IdSerializer::class) Id<T> {…}
    ). The custom serializer is declared as
    KSerializer<Id<*>>
    and it does not take any parameter. So far it works well, except that if I used it with a parameter that is not serializable (e.g.,
    Id<User>
    ), the compiler complains and I have to add a
    @Contextual
    annotation to the parameter. Is there a way to specify that the parameter is ignored? (for instance, using an annotation)
    d
    • 2
    • 2
Powered by Linen
Title
a

alightgoesout

02/09/2022, 1:00 PM
I have a generic class
Id<T>
where
T
is not actually used for serialization/deserialization. I have written a custom serializer for it that I have declared on the class (
@Serializable(with = IdSerializer::class) Id<T> {…}
). The custom serializer is declared as
KSerializer<Id<*>>
and it does not take any parameter. So far it works well, except that if I used it with a parameter that is not serializable (e.g.,
Id<User>
), the compiler complains and I have to add a
@Contextual
annotation to the parameter. Is there a way to specify that the parameter is ignored? (for instance, using an annotation)
d

Dominaezzz

02/09/2022, 6:33 PM
This seems like a bug. If your custom serialiser is not generic then the plug-in just ignore the generic parameter.
a

alightgoesout

02/10/2022, 9:51 AM
I have made a minimal repository to reproduce: https://github.com/alightgoesout/kotlinx-serialization-test If you confirm this is not the expected behavior I will open an issue.
View count: 10