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

    Deactivated User

    10/30/2020, 12:02 PM
    Hey guys, I was waiting for 1.0.0, nice work 🙂 I wonder if kotlinx.serialization can be easily be used for converting collection types to actual objects and vice-versa without actually serializing. Or iterate the fields of an object.
    c
    • 2
    • 5
  • p

    peekandpoke

    10/30/2020, 12:05 PM
    Hi there! I am looking for a way to decode a string into an object without having to know the serializer. Something like:
    val type: KType = ...
    val result = Json.decodeFromString(ktype, string)
    Does this functionality exist? Or asked the other way around: Is there something like a serializer-registry, that will give me the serializer for a given KClass or KType? Thanks!
    • 1
    • 1
  • c

    Christian Maier

    10/30/2020, 4:49 PM
    Hi there! I’ve just added Kotlin Serialization to my small Android project and now it won’t finish building. Does anyone else here had a similar issue?
    r
    • 2
    • 2
  • g

    Gilles Barbier

    10/30/2020, 5:12 PM
    Hello, I'm curious, is there an idiomatic way to know at run time if an Any object is serializable ?
    c
    t
    • 3
    • 3
  • t

    Tomasz Krakowiak

    11/02/2020, 4:07 PM
    Hello, is there any way to legitimately pass serializable parent constructor parameter from serializable child class with generated serializer?
    @Serializable
    sealed class A(
        val foo: String
    ) {
        @Serializable
        class B(
            foo: String,
            val bar: String,
    	) : A(foo)
    }
    Getting error "This class is not serializable automatically because it has primary constructor parameters that are not properties"
    • 1
    • 1
  • t

    Tomasz Krakowiak

    11/02/2020, 6:07 PM
    org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Failed to generate expression: KtNameReferenceExpression
    File being compiled: (40,39) in D:/work/workspace/boardgames/games/turingresistance/src/commonMain/kotlin/house/boardgames/games/turingresistance/model/deck/store/CardStore.kt
    The root cause java.lang.UnsupportedOperationException was thrown at: org.jetbrains.kotlin.codegen.context.CodegenContext.getOuterExpression(CodegenContext.java:222)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:335)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:293)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:414)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:422)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.gen(ExpressionCodegen.java:418)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl.genInitProperty(SerializableCodegenImpl.kt:279)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl.doGenerateConstructorImpl(SerializableCodegenImpl.kt:218)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl.access$doGenerateConstructorImpl(SerializableCodegenImpl.kt:38)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl$generateInternalConstructor$1.invoke(SerializableCodegenImpl.kt:81)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl$generateInternalConstructor$1.invoke(SerializableCodegenImpl.kt:38)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.JVMCodegenUtilKt$generateMethod$1.doGenerateBody(JVMCodegenUtil.kt:141)
    	at org.jetbrains.kotlin.codegen.FunctionGenerationStrategy$CodegenBased.generateBody(FunctionGenerationStrategy.java:86)
    	at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethodBody(FunctionCodegen.java:648)
    	at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethodBody(FunctionCodegen.java:483)
    	at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:259)
    	at org.jetbrains.kotlin.codegen.FunctionCodegen.generateMethod(FunctionCodegen.java:164)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.JVMCodegenUtilKt.generateMethod(JVMCodegenUtil.kt:138)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl.generateInternalConstructor(SerializableCodegenImpl.kt:81)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializableCodegen.generateSyntheticInternalConstructor(SerializableCodegen.kt:41)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializableCodegen.generate(SerializableCodegen.kt:33)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializableCodegenImpl$Companion.generateSerializableExtensions(SerializableCodegenImpl.kt:48)
    	at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationCodegenExtension.generateClassSyntheticParts(SerializationCodegenExtension.kt:29)
    	at org.jetbrains.kotlin.codegen.ImplementationBodyCodegen.generateSyntheticPartsAfterBody(ImplementationBodyCodegen.java:440)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:132)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:302)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:286)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:312)
    	at org.jetbrains.kotlin.codegen.ClassBodyCodegen.generateDeclaration(ClassBodyCodegen.java:176)
    	at org.jetbrains.kotlin.codegen.ClassBodyCodegen.generateBody(ClassBodyCodegen.java:80)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.generate(MemberCodegen.java:129)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:302)
    	at org.jetbrains.kotlin.codegen.MemberCodegen.genClassOrObject(MemberCodegen.java:286)
    	at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateClassesAndObjectsInFile(PackageCodegenImpl.java:119)
    	at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateFile(PackageCodegenImpl.java:138)
    	at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generate(PackageCodegenImpl.java:70)
    	at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generatePackage(CodegenFactory.kt:88)
    	at org.jetbrains.kotlin.codegen.DefaultCodegenFactory.generateModule(CodegenFactory.kt:67)
    	at org.jetbrains.kotlin.codegen.KotlinCodegenFacade.compileCorrectFiles(KotlinCodegenFacade.java:35)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.generate(KotlinToJVMBytecodeCompiler.kt:647)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:210)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli$default(KotlinToJVMBytecodeCompiler.kt:162)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:169)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:52)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:88)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:44)
    	at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:98)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:371)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:105)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:249)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:38)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:80)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compile(IncrementalCompilerRunner.kt:92)
    	at org.jetbrains.kotlin.daemon.CompileServiceImplBase.execIncrementalCompiler(CompileServiceImpl.kt:602)
    	at org.jetbrains.kotlin.daemon.CompileServiceImplBase.access$execIncrementalCompiler(CompileServiceImpl.kt:93)
    	at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:1644)
    	at jdk.internal.reflect.GeneratedMethodAccessor98.invoke(Unknown Source)
    	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    	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(AccessController.java:691)
    	at java.rmi/sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:587)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:828)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:705)
    	at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    	at java.rmi/sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:704)
    	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    	at java.base/java.lang.Thread.run(Thread.java:832)
    Caused by: java.lang.UnsupportedOperationException: Don't know how to generate outer expression: Class: class WordCardStore
    	at org.jetbrains.kotlin.codegen.context.CodegenContext.getOuterExpression(CodegenContext.java:222)
    	at org.jetbrains.kotlin.codegen.context.CodegenContext.lookupInContext(CodegenContext.java:563)
    	at org.jetbrains.kotlin.codegen.context.MethodContext.lookupInContext(MethodContext.java:83)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.findCapturedValue(ExpressionCodegen.java:2115)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.findLocalOrCapturedValue(ExpressionCodegen.java:2106)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.generateNonIntrinsicSimpleNameExpression(ExpressionCodegen.java:1986)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.visitSimpleNameExpression(ExpressionCodegen.java:1913)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.visitSimpleNameExpression(ExpressionCodegen.java:114)
    	at org.jetbrains.kotlin.psi.KtNameReferenceExpression.accept(KtNameReferenceExpression.kt:59)
    	at org.jetbrains.kotlin.codegen.ExpressionCodegen.genQualified(ExpressionCodegen.java:311)
    	... 70 more
    v
    • 2
    • 4
  • d

    Davide Giuseppe Farella

    11/03/2020, 8:33 AM
    Good morning, we have a json with a field
    type
    , we implemented the model with `sealed class`; serialization works flawlessly, but deserialization doesn’t include the field
    type
    . What is the best way to deal with it? We’re on 1.4.10
    i
    p
    • 3
    • 8
  • a

    Antoine Gagnon

    11/03/2020, 6:05 PM
    Hi all! Maybe a bit similar to the previous post, but I’m having issues understanding why the
    animalType
    field isn’t serialized in my code:
    @Serializable
    abstract class Animal{
        abstract val name : String
        abstract val animalType : String
    }
    
    @Serializable
    class Dog(override val name:String):Animal(){
        override val animalType: String = "Dog"
    }
    
    val rex = Dog("Rex")
    val string = Json.encodeToString(Dog.serializer(),rex)
    println(string)
    The
    string
    value at the end is always
    {"name":"Rex"}
    and doesn’t include the
    animalType
    field
    t
    i
    a
    • 4
    • 8
  • g

    Gilles Barbier

    11/05/2020, 5:31 PM
    Hi all, following my question here https://kotlinlang.slack.com/archives/C7A1U5PTM/p1604077940258100 - the only way to know at run time if an Any object is serializable and get serializer would be:
    fun <T : Any> getSerializer(obj: T) : KSerializer<T>? {
        val companionField = obj::class.java.declaredFields.find {
            it.name == "Companion" && isStatic(it.modifiers)
        } ?: return null
    
        val companion = companionField.get(obj)
        val serializerMethod = try {
            companion::class.java.getMethod("serializer")
        } catch (e: NoSuchMethodException) {
            return null
        }
    
        if (serializerMethod.returnType.name !=  KSerializer::class.qualifiedName) {
            return null
        }
    
        @Suppress("UNCHECKED_CAST")
        return serializerMethod.invoke(companion) as KSerializer<T>
    }
    Is it the right way? It's seem a bit cumbersome to me. Why not to add an interface?
    t
    • 2
    • 6
  • p

    Paul Woitaschek

    11/06/2020, 6:20 AM
    Is there any way to get the type of a polymorphic serialization? I'm serializing a sealed class to protobuf but I also need to know the unique
    type
    of the child class
    e
    • 2
    • 1
  • i

    Ivan Colovic

    11/09/2020, 10:32 AM
    Hi everyone. I’m trying to create a custom Serializer for the following class.
    class TreeNode(
        val value: MyData
    ) {
        val children = listOf<TreeNode>()
    }
    I’m trying to have the
    value
    field named dynamically based on its type (many classes inherit from
    MyData
    ). Something like:
    {
       "data_one":{
          ...
       },
       "children":[
          {
             "data_two":{
                ...
             },
             "children":[
                {
                   "data_three":{
                      ...
                   },
                   "children":[
                      
                   ]
                },
                {
                   "data_one":{
                      ...
                   },
                   "children":[
                      
                   ]
                }
             ]
          }
       ]
    }
    How do I define the
    SerialDescriptor
    element that represents the collection of its own type? Right now, I have:
    override val descriptor: SerialDescriptor = buildClassSerialDescriptor("TreeNode") {
            element<DataOne>("data_one")
            element<DataTwo>("data_two")
            element<DataThree>("data_three")
            element("children", listSerialDescriptor<TreeNode>()) // this crashes because I'm trying to use the descriptor I'm currently creating
        }
    When I change the
    listSerialDescriptor<TreeNode>()
    to for example
    listSerialDescriptor<String>()
    it encodes it the way I want it to, but I'm getting errors when decoding. How do I approach this? Still new to the library I hope I was clear enough 🙇‍♂️ Thanks!
    n
    • 2
    • 5
  • m

    Marc Plano-Lesay

    11/12/2020, 2:37 AM
    Hi, I'm finally upgrading from Kotlin 1.3 to 1.4, and kotlinx.serialization from 0.20 to 1.0.1 at the same time. I was relying on
    JsonDecodingException
    and
    MissingFieldException
    being visible to slightly alter my error messages. They're now internal (defined here: https://github.com/Kotlin/kotlinx.serialization/blob/v1.0.1/core/commonMain/src/kotlinx/serialization/SerializationException.kt). Is there a way to get that distinction post 0.20?
    • 1
    • 1
  • n

    Nish Patel

    11/12/2020, 5:15 PM
    i'm new to kotlin and i need help in regarding parsing json to sealed class using kotlin.serialization library, whats the difference between serializer and serialName
    b
    • 2
    • 3
  • p

    pajatopmr

    11/13/2020, 1:55 PM
    I've been through the serialization guide (very impressive piece of work) but how to deal with custom deserializers for polymorphic classes (cannot use "type" discriminant) has eluded me. Can someone refer me to which section(s) of the guide might contain the information I need?
    v
    • 2
    • 5
  • e

    Emerson Farrugia

    11/17/2020, 10:11 AM
    Hi 👋 There wasn't an answer to this 5 months ago, wondering if anything's changed. I'm trying to reuse chunks of related properties in DTOs, but the current API has them all flattened out. 😕
    v
    • 2
    • 1
  • b

    bram93

    11/17/2020, 7:39 PM
    Hi, I was wondering, could
    kottlinx.serialization
    be utilized to parse a
    GraphQLType
    (from graphql-java) and map it to a POJO without reflection costs? Using a custom format of some sort?
    b
    v
    +2
    • 5
    • 7
  • b

    bbaldino

    11/17/2020, 10:22 PM
    Is it possible to define a method such that it only accepts
    @Serializable
    types? I have a method that I want to be able to accept any type (Int, Boolean, some object, etc.) such that it can be serialized to Json via
    encodeToString
    c
    • 2
    • 2
  • s

    Shan

    11/18/2020, 7:29 PM
    Hey all. I have an error with Intellij where the
    serializer()
    function is not being recognized, nor the
    @Serializable
    annotation, but the dependencies are being built correctly and everything works as intended. The
    @Serializable
    annotation has a warning that the Kotlinx.Serialization compiler plugin is not applied to the module (which is not true), and the
    Foo.serializer()
    function is showing up as not being found (I'm assuming as a result of Intellij thinking that the kotlinx.serialization compile plugin not being applied). Anyone know how to fix this? I've updated my Intellij to the latest version, as well as Kotlinx.Serialization library to no avail.
    a
    k
    • 3
    • 2
  • i

    Igor Brishkoski

    11/20/2020, 9:23 PM
    I wrote a deserializer for a List of type Any
    List<Any>
    and it works fine when I try to encode/decode the list on it’s own with
    Json
    When I added it to my class, which is a member of a sealed class, I get this error.
    Serializer has not been found for type 'Any'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
    @Serializable
        @SerialName("Sign")
        data class Sign(
            @Serializable(with = ListAnySerializer::class)
            val payload: List<Any>
        ) : SealedClass()
    a
    • 2
    • 1
  • j

    jaguililla

    11/21/2020, 4:35 PM
    Hi. Do you know if
    kotlinx.serialization
    provides the functionality to convert a
    Map
    to a type as Jackson’s
    ObjectMapper.convertValue
    do? Thanks!
    b
    • 2
    • 5
  • b

    BollywoodVillain

    11/23/2020, 5:46 PM
    Hi, n00b Kotlin dev here: Is there a way to convert the `val`s in the
    @Serializable
    data class while encoding? e.g. Given a data class: data class
    MyClass(val accessible: Boolean)
    and given the input JSON
    { "accessible": "yes" }
    , can we convert the
    accessible
    to
    Boolean
    from
    String
    while encoding?
    r
    • 2
    • 4
  • b

    BollywoodVillain

    11/24/2020, 7:00 AM
    How do we flatten a JSON with nested elements into a single class? E.g. I’ve to following OSM data that I need to have in just one class, without creating a subclass for `tags`:
    {
      "type": "node",
      "id": 66917229,
      "lat": 52.5167295,
      "lon": 13.3797732,
      "tags": {
        "addr:city": "Berlin",
        "addr:housenumber": "4a",
        "addr:postcode": "10117",
        "addr:street": "Pariser Platz",
        "amenity": "cafe",
        "brand": "Starbucks",
        "name": "Starbucks",
        "website": "<https://www.starbucks.de/store-locator/store/2099/pariser-platz-pariser-platz-4-a-berlin-be-10117-de>",
        "wheelchair": "yes",
        "wifi": "free"
      }
    }
    I am using custom Serializer but I’m a bit lost on how to unwrap the nested values in the
    deserialize
    function for the nested tags element. Any help is highly appreciated.
    r
    v
    • 3
    • 8
  • c

    Chris Ruddell

    11/24/2020, 4:34 PM
    Is there any way to serialize a generic/Any object, if the actual implementation class was marked with
    @Serializable
    ? I have a lot of classes marked with
    @Serializable
    , but would like to have a single function to serialize them into JSON. For instance, something like
    fun Any.toJson(): String = serializer.encodeToString(this)
    Here’s what I’ve tried:
    class JsonTest {
    
        val serializer = Json {
            serializersModule = SerializersModule {
                contextual(MyModel.serializer())
            }
        }
    
        // this works
        fun MyModel.toModelJson(): String = serializer.encodeToString(this)
    
        // this does not
        fun Any.toJson(): String = serializer.encodeToString(this)
    
        @Serializable
        data class MyModel (val name: String)
    
        @Test
        fun testJson() {
    
            val model = MyModel("test")
            val modelJson = model.toModelJson()
            assertTrue(modelJson.isNotEmpty())
    
            val genericJson = model.toJson()
            assertTrue(genericJson.isNotEmpty())
        }
    }
    Exception thrown:
    kotlinx.serialization.SerializationException: Serializer for class 'Any' is not found.
    m
    • 2
    • 2
  • t

    TwoClocks

    11/24/2020, 7:48 PM
    does typealias information survive serialization?
    b
    a
    p
    • 4
    • 41
  • r

    rocketraman

    12/01/2020, 2:52 PM
    I'm trying to use Avro4k with Apache Beam by creating a generic
    CustomCoder
    implementation that can handle any
    @Serializable
    . Avro4k needs a
    KSerializer<T>
    . How can I obtain the
    KSerializer
    at runtime? Keep in mind that in Beam
    Coder
    needs to be serializable itself, so
    KSerializer
    or
    KType
    cannot be a property of the coder i.e. this does not work, nor does passing in `KType`:
    class Avro4kCoder<T: Any>(private val serializer: KSerializer<T>): CustomCoder<T>() {
      override fun encode(value: T, outStream: OutputStream) {
        Avro.default.openOutputStream(serializer) {
          encodeFormat = AvroEncodeFormat.Binary
        }.to(outStream).write(value).flush()
      }
      override fun decode(inStream: InputStream): T? {
        return Avro.default.openInputStream(serializer) {
          decodeFormat = AvroDecodeFormat.Binary(Avro.default.schema(serializer))
        }.from(inStream).next()
      }
    }
    v
    g
    • 3
    • 17
  • r

    rocketraman

    12/01/2020, 6:47 PM
    Let me ask the question again in a different way. Obviously its possible to retrieve a serializer if one knows the type e.g.:
    val stringToColorMapSerializer: KSerializer<Map<String, Color>> = serializer()
    However, is it possible to retrieve a serializer generically? Since
    class
    definitions can't have reified
    T
    , the normal workaround is to pass in a
    Class<T>
    . If I know that
    T
    is an
    @Serializable
    can I get the
    KSerializer<T>
    from
    Class<T>
    ?
    e
    r
    • 3
    • 13
  • c

    Chris Fillmore

    12/03/2020, 4:18 PM
    The only thing I want to serialize in the above is the
    headers
    , which I can get from
    toMap()
    r
    • 2
    • 3
  • t

    Thomas

    12/03/2020, 8:20 PM
    I noticed that kotlinx.serialization has support for Linux arm targets. It would be great if you could share how you set up testing for those targets. I would really like to see Linux arm support for kotlinx.coroutines but it is unsupported due to testing. Could someone from kotlinx.serialization please share their experience here? https://github.com/Kotlin/kotlinx.coroutines/issues/855
    v
    • 2
    • 2
  • b

    Byron Katz

    12/05/2020, 5:08 PM
    I want to catch on that so I can switch it to our own application exception, but in the current circumstances all I can do is catch on a general exception.
    m
    b
    • 3
    • 4
  • p

    pajatopmr

    12/06/2020, 3:29 PM
    I am trying to model a TypeScript document using Kotlin. No small challenge. Any suggestions on how to model something like this snippet:
    someProvider?: boolean | string | SomeOptions;
    My current solution is to create a sealed class
    SomeProvider
    with subclasses:
    BooleanProvider
    ,
    StringProvider
    , and
    OptionsProvider
    so that I have the Kotlin snippet,
    someProvider: SomeProvider?
    which works but feels sub-optimal. Alternative suggestions much appreciated.
    a
    • 2
    • 2
Powered by Linen
Title
p

pajatopmr

12/06/2020, 3:29 PM
I am trying to model a TypeScript document using Kotlin. No small challenge. Any suggestions on how to model something like this snippet:
someProvider?: boolean | string | SomeOptions;
My current solution is to create a sealed class
SomeProvider
with subclasses:
BooleanProvider
,
StringProvider
, and
OptionsProvider
so that I have the Kotlin snippet,
someProvider: SomeProvider?
which works but feels sub-optimal. Alternative suggestions much appreciated.
a

andylamax

12/06/2020, 9:03 PM
what do you mean when you say you trying to model a TS document? What is your end goal?
p

pajatopmr

12/06/2020, 9:57 PM
That is a way too open question, but I'll be brief: my goal is to replace Jacoco for Kotlin with a better tool that works on the source rather than an intermediate form and to get there it would be good to have a library that supports Microsoft's LSP. Since LSP is specified using TypeScript and since Kotln is my language of choice these days a TypeScript interface to a Kotlin something is necessary. There is LSP4E/J but I'd rather keep it pure Kotlin and eventually get to a MPP final result. While I do enjoy talking about the end goal, the serialization issue at hand will be much more helpful. Have I given you enough information so you can offer a suggestion? You can see some of my early work up on GitLab and the LSP spec is here.
View count: 14