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

    altavir

    04/11/2020, 5:34 PM
    Another question (everything is working, but I want to make it more foolproof. I am serializing a double-linked tree (parent references children and children reference parent, so after deserialization I have to run a function to "attach" children to the partent. Currently I just use a serialization wrapper that does it after deserialization. Is there a better way? Some time ago I asked aboud after-deserialization-hooks and there were not any. Are there any changes?
    t
    • 2
    • 3
  • r

    rharter

    04/15/2020, 3:13 PM
    I’m getting an 
    InvocationTargetException
     due to a 
    NoClassDefFoundError
     when trying to invoke the serializer() method on a 
    @Serializable
     class.  The class and method are found (via reflection using Ktor’s kotlinx.serialization content negotiation feature) and set accessible, but this still happens.  The annotated data class is public, but in a dependent module from the actual server that is executed. Any idea what might be wrong?
    s
    r
    • 3
    • 28
  • f

    fkrauthan

    04/16/2020, 9:57 PM
    Hey I am currently stuck trying to write a custom serializer. I pretty much get a JSON that contains a list of strings. But instead of having that list of strings (which are base64 encoded strings) I would like to write a serializer that takes in the string and decodes it before saving it in the internal data class
    t
    • 2
    • 2
  • s

    SrSouza

    04/17/2020, 3:41 PM
    Hi folks, there is anyway to add a new annotation and use to map primitive types. Example:
    @Abs val num: Int
    =>
    {"num": -3}
    that deserialize to 3. I already create my owns annotation for Kotlinx.serialization, I know that supports it, but was for a new Enconder of mine, not from a existing one like Json.
    d
    • 2
    • 4
  • s

    Sam Garfinkel

    04/17/2020, 9:31 PM
    Is there a way with reified generics to safely get a
    serializer
    from a generic
    T
    at compile-time? I know about
    KClass<T: Any>.serializer()
    but that relies on reflection. Likely doesn’t exist, but it would be cool to be able to mark a generic reified argument as
    @Serializable
    too (maybe limited to
    internal
    or
    private
    so that the constraint could be validated at compile time) so the compiler can validate it’s not used improperly and also to allow compile-time optimization of the inlined code to get the Serializer companion/object that’s available.
    k
    • 2
    • 3
  • s

    SrSouza

    04/18/2020, 9:58 PM
    Folks, I create a new Serializer for a Primitive type( String ), when I use it in the String type, works perfectly, but with List<String> does not. Its given me this exception:
    Caused by: java.lang.ClassCastException: kotlin.collections.EmptyList cannot be cast to java.lang.String
    How can I make my Serializer works in List and Map? My currently serializer.
    @Serializer(forClass = String::class)
    object ChangeColor : KSerializer<String> { ... }
    Usage that is causing this exception:
    @Serializable(with = ChangeColor::class)
    val messages: List<String> = listOf()
    d
    • 2
    • 8
  • s

    SrSouza

    04/19/2020, 9:42 PM
    Hi folks, there anyway to in a specific property usa other type of StringFormat or set at the data class? I'm trying to do something like this (code in the thread), use Json StringFormat but in a specific data class, use CSV StringFormat. But is getting exception because the compiler overrides the default
    .serializer()
    to this new that I created.
    s
    • 2
    • 4
  • g

    ghosalmartin

    04/22/2020, 11:27 AM
    I've noticed though the nullables are causing an issue, do they need to be given a default value of null?
    s
    • 2
    • 2
  • a

    Antanas A.

    04/22/2020, 11:36 AM
    Hello, is it possible to parse JSON to data class not directly from string, but from JsonObject/JsonElement without converting it back to String and then do "parse"?
    • 1
    • 1
  • a

    Antoine Gagnon

    04/22/2020, 2:00 PM
    Hey everyone, I’m having some issues with my test coverage with the
    patch
    method generate by the @Serializable annotation. I can’t seem to figure out how to get a decoder to test it?
    s
    • 2
    • 2
  • c

    crummy

    04/23/2020, 10:53 PM
    I'm trying to get javalin to use kotlinx.serialization instead of Jackson. I found this on their github page:
    JavalinJson.toJsonMapper = object : ToJsonMapper {
         override fun map(obj: Any) =  { /* Your implementation here */ }
    }
    I tried this:
    JavalinJson.fromJsonMapper = object : FromJsonMapper {
            override fun <T> map(json: String, targetClass: Class<T>): T {
                return Json.parse(T::class.serializer(), json)
            }
        }
    But get
    Unresolved reference: serializer
    . Is this how to go about it?
    s
    • 2
    • 3
  • c

    crummy

    04/26/2020, 1:38 AM
    I've got a method that fails to deserialize:
    fun getAll(): Collection<User>
    I get:
    kotlinx.serialization.SerializationException: Can't locate argument-less serializer for class LinkedValues. For generic classes, such as lists, please provide serializer explicitly.
    I think I need to somehow indicate that this method should deserialize with
    User.serializer().list
    . But I'm not sure how to do that.
    • 1
    • 2
  • c

    crummy

    04/28/2020, 5:27 AM
    I've got a data class with an inner LocalDate that I've annotated with
    @Serializable(with = LocalDateSerializer::class)
    (LocalDateSerializer is a class I've created.) However, now I'm returning a
    Map<LocalDate, foo>
    elsewhere and getting an error
    Can't locate argument-less serializer for class LocalDate
    . How do I annotate this?
    p
    b
    • 3
    • 5
  • a

    Animesh Sahu

    04/28/2020, 2:09 PM
    Is there a way to accept Serializable types in a function? Like some supertypes or something? Usecase:
    fun <T : Any> store(key: String, value: T, serializer: KSerializer<T>) {
        json.stringify(serializer, value)
    }
    
    //To, maybe reified
    fun <T : SomeSuperTypeForSerializable> store(key: String, value: T) {
        json.stringify(T.serializer(), value)
    }
    n
    b
    • 3
    • 7
  • b

    basher

    05/01/2020, 7:51 PM
    What's the best way to get serialization to represent null values as Json
    null
    , instead of having the key, value pair not present (in a dict)?
    • 1
    • 1
  • p

    Paul Woitaschek

    05/04/2020, 10:19 AM
    It would be so great to have some way of global discovery. I now have about 70 occurences in my project of `
    @Serializable(with = LocalDateSerializer::class)
    👍 1
    c
    b
    • 3
    • 24
  • d

    dagomni

    05/05/2020, 4:30 PM
    Hi, I'm working on a project where null objects sometimes are being returned as [ ]. Serializer expects an object but there's an array in its place in json. Is there a way to deal with incorrect types?
    r
    • 2
    • 2
  • d

    dagomni

    05/06/2020, 8:54 AM
    To bump my previous question: Does anyone know if there's a way to apply JsonTransformingSerializer to every possible type, without specifying the type explicitly? I'm basically looking for a way to implement this, which was quite easy to do in Moshi https://pastebin.com/hmdwERm9 (snippet stolen from @jw - https://github.com/square/moshi/issues/295#issuecomment-299610834)
    d
    • 2
    • 2
  • d

    dagomni

    05/06/2020, 12:45 PM
    I have another question 😏 Using polymorphism AND generics
    @Serializable
    sealed class Response<T> {
        @Serializable
        data class ResponseData<T>(
            @SerialName("data")
            val data: T
        ) : Response<T>()
    
        @Serializable
        data class AuthData(
            @SerialName("data")
            val data: AdditionalAuthorization?
        ) : Response<AdditionalAuthorization?>()
    }
    I get this error
    Unexpected JSON token at offset 0: Expected '[, kind: SEALED'.
    It fails even with the simplest json. Apart from sealed classes I've also tried interface, open, abstract - same error, different kind given in message. Is what I'm trying to achieve supported by kotlinx.serialization?
    d
    • 2
    • 3
  • s

    Shan

    05/14/2020, 5:59 AM
    Anyone happen to know why my serializer I've written for an enum class is failing with this
    JsonDecodingException
    ? What is strange is that it works in certain cases, but fails in others. When I get back this response:
    {
      "id": 1,
      "status": 1,
      "info": 0
    }
    It works fine and returns
    IN_PROGRESS
    . When I get this response:
    {
      "id": 3,
      "status": 3,
      "info": 0
    }
    I encounter this error:
    kotlinx.serialization.json.JsonDecodingException: Invalid JSON at 28: Expected string or non-null literal
    Which is thrown from
    takeString()
    in
    JsonReader.kt
    after trying to call
    decodeInt()
    . If both of them were failing I would be a little less confused, but with only one of them failing I am at a loss. Is it interpreting the
    3
    as a byte or something, and thus failing the
    TC_OTHER
    and
    TC_STRING
    check, whereas the
    1
    is interpreted as a
    TC_STRING
    somehow? All I can think of 🤔
    Untitled.kt
    t
    n
    • 3
    • 15
  • b

    bsimmons

    05/14/2020, 2:45 PM
    Hey all, I'm working with a messy REST API that requires JSON keys that change based upon table name. So a simple Json.stringify() isn't really going to work in this case. Is there a a low-level API in kotlinx.serialization.json that allows me to dynamically create JSON strings to send. (I would use a lib like klaxon, but I am using Kotlin MPP.) Any ideas?
    s
    • 2
    • 2
  • m

    MrPowerGamerBR

    05/18/2020, 10:00 PM
    Not sure if it is intentional but... is it necessary to add
    @Serializable
    to enums? I'm having issues with enums without the
    @Serializable
    annotation in JavaScript (haven't tested in the JVM yet)
    t
    • 2
    • 8
  • f

    Franco

    05/21/2020, 4:33 AM
    Hi everyone, I'm getting the following error when parsing sealed classes in Kotlin/JS:
    type is not registered for polymorphic serialization in the scope of class
    This is my code:
    @Serializable
    sealed class TestClass {
    
        @Serializable
        @SerialName("TEST_1")
        data class TestClass1(
            val value1: String,
            val value2: Int
        ) : TestClass()
    
        @Serializable
        @SerialName("TEST_2")
        data class TestClass2(
            val value1: String
        ) : TestClass()
    
    }
    I found this link where the issue is discussed: https://github.com/Kotlin/kotlinx.serialization/issues/457 and seems like a fix is ready (but not yet released). I was wondering if there is a workaround that allows us to make it work until the fix is released? (I know that I can do this using a Serializer but not sure how to build it in a way that I can remove it once the fix for this is released and nothing will break).
    t
    • 2
    • 2
  • k

    Kroppeb

    05/21/2020, 12:02 PM
    I am making a new
    Encoder
    /
    Decoder
    and I'm confused why there is a
    Encoder
    and a
    CompisiteEncoder
    . Why does there need to be a destiction?
    r
    • 2
    • 2
  • s

    Sam Garfinkel

    05/21/2020, 5:16 PM
    Is there a list of built-in serializers anywhere? I’ve looked in
    commonMain
    at the built-ins there, but there are some other types that the IDE isn’t complaining about, like
    java.nio.Path
    .
    d
    • 2
    • 3
  • p

    Patrick

    05/22/2020, 12:43 PM
    I get this error message when I annotate a class with Serializable
    Cannot access 'Serializable': it is internal in '<http://kotlin.io|kotlin.io>'
    n
    r
    • 3
    • 24
  • p

    Patrick

    05/25/2020, 8:42 AM
    I have the following problem regarding serialization of polymorphic enum classes:
    interface ExampleInterface
    
    @Serializable
    enum class Example: ExampleInterface {
        TEST,
        TEST2
    }
    
    
    @Serializable
    enum class Example2: ExampleInterface {
        WOW,
        WOW2
    }
    
    @Serializable
    data class ExampleWrapper(val m: ExampleInterface)
    
    fun main() {
    
        val module = SerializersModule {
            polymorphic(ExampleInterface::class) {
                Example::class with Example.serializer()
                Example2::class with Example2.serializer()
            }
        }
    
        val json = Json(JsonConfiguration.Stable, context = module)
        val jsonData = json.stringify(ExampleWrapper.serializer(), ExampleWrapper(Example.TEST))
        println(jsonData)
    }
    When I run this, the following error message is displayed:
    Uncaught Kotlin exception: kotlin.IllegalStateException: Enums cannot be serialized polymorphically with 'type' parameter. You can use 'JsonConfiguration.useArrayPolymorphism' instead
    Now if I do what the error message says, I will get back something like this:
    {
      "m": [
        "barcodeParser.Example",
        "TEST"
      ]
    }
    But I would rather have it look like this:
    {
      "m": "TEST"
    }
    How can I achieve this?
    k
    • 2
    • 5
  • p

    Patrick

    05/26/2020, 9:51 AM
    Also is there a way to automatically serialize types in Kotlin Native? It seems very hard to automatically parse primitive types to the correct Kotlin type. For example ["foo", 1, 1.0] should automatically be parsed to kotlin.String, kotlin.Int, kotlin.Float.
    k
    • 2
    • 49
  • e

    edenman

    05/26/2020, 9:24 PM
    i’ve got a class
    Foo
    that i want to deserialize to null if the server gives me
    {}
    for the json. started to implement a
    JsonTransformingSerializer
    but it has a type bound
    <T: Any>
    which appears to mean I can’t create a `JsonTransformingSerializer<Foo?>`…I’ve worked around it for now by adding the custom serialization logic on every object that has a Foo, but that’s far from ideal
    d
    • 2
    • 6
  • s

    Sean Keane

    05/28/2020, 9:20 PM
    Hi, does anyone know how to deserialise an enum from a string?
    @Serializable
    enum class Error(@SerialName("code") val code: String? = null) {
        UNEXPECTED("0001")
    }
    If I pass it a json string of the following I want it to create an enum response.
    {
      "code": "0001"
    }
    I used to use CommonEnumSerializer but its been deprecated. Is there an alternative?
    a
    p
    k
    • 4
    • 11
Powered by Linen
Title
s

Sean Keane

05/28/2020, 9:20 PM
Hi, does anyone know how to deserialise an enum from a string?
@Serializable
enum class Error(@SerialName("code") val code: String? = null) {
    UNEXPECTED("0001")
}
If I pass it a json string of the following I want it to create an enum response.
{
  "code": "0001"
}
I used to use CommonEnumSerializer but its been deprecated. Is there an alternative?
Just a note, the reason I want this is because all the other examples show an enum nested in a data class. But all I need is the object
a

ankushg

05/28/2020, 10:16 PM
I had to create a custom deserializer to handle this
s

Sean Keane

05/29/2020, 12:23 AM
Do you have an example by any chance? I was using the custom CommonEnumSerializer but I can't seem to use it with 0.20.0
p

Patrick

05/29/2020, 12:50 PM
https://kotlinlang.slack.com/archives/C7A1U5PTM/p1590407955212000?thread_ts=1590396123.209300&amp;cid=C7A1U5PTM
This is for polymorphic serialization but if you amend it a bit it should work for you.
s

Sean Keane

05/29/2020, 1:54 PM
I'll give this a try! Thank you 👏
👍 1
Ok, that didnt work for me so I decided to just use a filter.
Error.values().first { it.errorCode == "0001" }
k

Kroppeb

05/29/2020, 5:47 PM
What was the error it gave?
s

Sean Keane

05/29/2020, 6:03 PM
I changed the approach as this was to merge two enums and return an interface, what I needed to do was construct an enum based on a param.
p

Patrick

06/02/2020, 10:26 AM
How exactly did you solve it?
s

Sean Keane

06/02/2020, 12:55 PM
return YOURENUMCLASS.values().first { it.errorCode == code }
👍 1
View count: 5