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

    pajatopmr

    12/07/2020, 4:19 PM
    A more general statement of my previous question for dealing with the Language Server Protocol (LSP) might be: when encountering a single JSON element (same name == "fieldName") that can be a primitive (
    "fieldName":234
    ), a structure (
    "fieldName":{...}
    ) or an array (
    "fieldName":["string1","string2","string3"]
    ), what is the most logical/appropriate KSX feature for handling the serialization of that JSON element. JsonContentPolymorphicSerializer has proven to be very helpful for "regular" TypeScript <-> Kotlin interface mappings, i.e. interface constructs that appear nearly the same in both languages. It is when TypeScript can have one of primitive, object and/or array JSON elements that it gets much harder, at least as I understand KSX so far. My current thinking is that the most likely feature to use is the experimental one ("Under the hood") in the Json Transformations in the fifth chapter of the Kotlin Serialization Guide. If there is an easier approach, I'd love to hear about it.
    n
    • 2
    • 2
  • a

    andylamax

    12/08/2020, 5:55 AM
    All over a sudden,
    Person.serializer().list
    can't be resovled. How do I get a list serializer in
    kotlinx-serilialization-1.0.1
    ?
    r
    • 2
    • 2
  • a

    Azur Haljeta

    12/08/2020, 8:09 PM
    Is there any quick API to put a simple value into a
    JsonObject
    without unboxing the whole object?
    r
    p
    • 3
    • 7
  • p

    pajatopmr

    12/10/2020, 10:37 PM
    My next serialization challenge is to conjure up a serializer for the abstract class Number. My first guess would be to use @Contextual. Good guess? But since I may have to tweak the actual Json, JsonTransformingSerializer might be better.
    • 1
    • 1
  • a

    adk

    12/11/2020, 10:38 AM
    Is there a way to have a subclass serialized with the custom serializer of its superclass, without having to declare
    @Serializable(with= ... )
    on every subclass?
    j
    • 2
    • 14
  • m

    Marc Knaup

    12/11/2020, 1:13 PM
    Is there any easy way to (de)serialize purely through an
    interface
    ? That is, without adding any support for serialization to the implementing
    class
    , and when deserializing have the compiler generate an
    object
    that implements the
    interface
    .
    @Serializable
    interface Foo {
    	val bar1: String
    	val bar2: Int
    }
    Should serialize too
    {"bar1":"…","bar2":…}
    independent of the implementing
    class
    .
    {"bar1":"abc","bar2":42}
    should deserialize to
    object : Foo { override val bar1 = "abc"; override val bar2 = 42 }
    .
    n
    • 2
    • 2
  • m

    Marc Knaup

    12/12/2020, 2:53 AM
    Class
    ArrayList
    is not registered for polymorphic serialization in the scope of
    Any
    . Mark the base class as
    sealed
    or register the serializer explicitly.
    Class
    SingletonList
    is not registered for polymorphic serialization in the scope of
    Any
    . Mark the base class as
    sealed
    or register the serializer explicitly.
    Do I really have to do this dance for every possible implementation of
    Collection
    ? 😮 Also, how do I register subclasses of
    Collection
    ? There’s no
    Collection.serializer()
    or
    ArrayList.serializer()
    I could use for polymorphism 🤔
    j
    • 2
    • 5
  • r

    russhwolf

    12/12/2020, 10:46 PM
    The kotlinx.serialization Json format is able to fall back on default values if something is missing during decoding. So if you have a class
    @Serializable
    data class Foo(val bar: String = "bar")
    and deserialize an empty json object
    val foo = Json.decodeFromString(Foo.serializer(), "{}")
    then you get
    Foo("bar")
    as output rather than an error or
    Foo("")
    or something else. Can anyone point to what makes that happen? I want to do something similar for a custom format. (NB I’m not looking for the
    encodeDefaults
    option. That flag controls whether default values are added to Json output. I’m looking for how default values are inferred when missing from Json input.)
    p
    d
    • 3
    • 7
  • t

    tieskedh

    12/16/2020, 7:28 PM
    I've a question: I've an api that returns information for the pagination and the list of items in the same object:
    {
         "offset":0,
         "limit":15,
         "count":1,
         //and a field with custom fieldname with the items
         "fooItems": [...]
    }
    Can I transform this somehow in a class like this:
    class PaginationResult<T>(
        val offset : Int,
        val limit : Int,
        val count : Int,
        val items : List<T>
    }
    @Serializable FooItem
    @serializable BarItem
    j
    • 2
    • 11
  • p

    pajatopmr

    12/17/2020, 10:30 PM
    As I understand the JSON spec, there is no order dependence on fields on a JSON object:
    {"foo":"fooValue","fee":"feeValue"}
    and `{"fee":"feeValue","foo":"fooValue"}`should deserialize to the same object. But this is apparently not the case with KXS. Is there some fine print that says JSON implementors can do pretty much what they want or is this a bug of some sort? My assumption is the former so that means transforming incoming JSON to a correct order. Any chance I have this assumption wrong?
    v
    h
    • 3
    • 8
  • c

    Chris Fillmore

    12/18/2020, 3:02 PM
    Hello. I was previously using serialization-core
    1.0.0-RC
    and updated to serialization-json
    1.0.1
    and it seems there is a change in behaviour for this use case:
    @Serializable
    class MyClass(
      val id: String
    ) {
      val message = "my message"
    }
    This is my serialization code:
    val serializer = Json {
      // Not relevant to the example but this is the Json serialization config I'm using
      ignoreUnknownKeys = true
      prettyPrint = true
    }
    val myClass = MyClass("abc123")
    val serialized = serializer.serialize(myClass)
    I expect
    serialized
    to be
    {
      "id": "abc123",
      "message": "my message"
    }
    but I’m getting
    {
      "id": "abc123"
    }
    m
    • 2
    • 3
  • j

    jaqxues

    12/19/2020, 5:51 PM
    Is there no way to pack the proguard.rules into a consumer.rules in kotlinx.serialization? so the library itself applies the rules needed for kotlinx serialization?
    j
    • 2
    • 5
  • o

    Offz

    12/22/2020, 4:15 AM
    Hello, I have a serializable class that holds one parameter (a map) and I'd like to be able to serialize it directly using that map's serializer, without the parameter name. I've managed to write my own serializer that just uses a map serializer and its descriptor to do this, and it works exactly how I want. The only issue is, I now want to use this with polymorphic serialization and I can't seem to find a way to change the SerialName. Is there a better way to do this, or any way to change the SerialName on an existing descriptor? Thanks in advance!
    • 1
    • 1
  • j

    Javier

    12/22/2020, 1:06 PM
    with kotlin 1.4.30 M1, the support for inline classes is coming?
    v
    • 2
    • 3
  • u

    ursus

    12/23/2020, 4:07 AM
    Does kotlix serialization json have streaming? I remember it not being supported yet, now I notice StreamingJsonDecoder in the code base so.. is it? (But I have checked changelogs and no mention)
    j
    • 2
    • 2
  • r

    Rodrigo Silva

    12/23/2020, 1:18 PM
    Hello all, i'm trying to use kotlinx, but i'm getting this error:
    kotlinx.serialization.SerializationException: Serializer for class 'Immobile' is not found.
    Mark the class as @Serializable or provide the serializer explicitly.
    j
    • 2
    • 3
  • r

    Robert Jaros

    12/23/2020, 5:40 PM
    Any idea why Kotlin 1.4.30-M1 does not allow
    @file:UseContextualSerialization
    annotation (both with IR and Legacy)?
    t
    • 2
    • 2
  • u

    ursus

    12/24/2020, 4:23 PM
    Is there a way to check @Serializable annotation at compile time? I'm getting burned at runtime and that's often too late
    j
    v
    • 3
    • 9
  • c

    camdenorrb

    12/25/2020, 2:36 PM
    Any idea why I can't serialize a generic class that's inside a sealed class with the Message serializer?
    j
    • 2
    • 6
  • e

    eygraber

    12/30/2020, 2:50 AM
    Is there any chance of infix functions being added back to
    JsonObjectBuilder
    (named something other than
    to
    )? It felt more fluid that way than using
    put
    n
    • 2
    • 3
  • p

    pajatopmr

    01/02/2021, 11:42 AM
    In the attached screen shot, I show three classes, A, B and C. A and B use interfaces and all is well. C uses a list of implementations and it passes but I would like to use a list of interfaces, as in B. When I change C to use a list of interfaces (by commenting line 48 and uncommenting line 49) the test fails with a polymorphism error message as indicated. Is there an obvious solution to this problem?
    d
    • 2
    • 16
  • j

    jaqxues

    01/02/2021, 8:06 PM
    I want to use kotlinx.serialization, but we also really need strong obfuscation. Is there any way to use kotlinx.serialization (with retrofit) that would allow me to ignore the proguard rules, and move back to full obfuscation?
    d
    • 2
    • 4
  • d

    dagomni

    01/03/2021, 2:58 PM
    For me this release still doesn't work when combining Compose and Serialization https://github.com/JetBrains/kotlin/releases/tag/v1.4.21-2
    j
    • 2
    • 3
  • p

    pajatopmr

    01/10/2021, 4:33 PM
    Looking for some clarification on missing fields: in the code shown below all is well if both fields have valid content. When the
    serverInfo
    field is missing, a missing field exception is thrown which I did not expect (because of the nullable indication). My conclusion is that this means I need to detect missing fields (using a transforming polymorphic serializer) and explicitly add a null, as in
    {"serverInfo":null}
    . Would that conclusion be correct or am I missing something?
    • 1
    • 1
  • p

    Piotr Prus

    01/15/2021, 2:26 PM
    Hi 👋 , first post here 🙂 I have a problem adding
    serialization-protobuf
    to my android project. This is what I am doing. in project level build.gradle:
    buildscipt {
    dependencies {
            classpath "org.jetbrains.kotlin:kotlin-serialization:${versions.kotlin}"
    }
    }
    
    apply plugin: 'org.jetbrains.kotlin.plugin.serialization'
    in app-level build.gradle:
    plugins {
        id 'kotlinx-serialization'
    }
    dependencies {
        implementation "org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.4.20"
    }
    I got following error:
    Could not find org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.4.20
    I believe I wrongly configured the plugins, but I do not found any guide for android. All of them are for multiplatform 🙂 . Can anyone point me where the issue is?
    r
    n
    • 3
    • 4
  • b

    bod

    01/17/2021, 4:46 PM
    Hello, World! I have a JSON API returning numbers, but apparently
    kotlin.Number
    is not Serializable. What's the easiest way to deal with this?
    j
    • 2
    • 4
  • m

    Michael

    01/17/2021, 5:48 PM
    Hey, I currently have a problem with a sealed class on kotlin/js (IR) I can only use encodeTo/decodeFromString when specifiyng the serializer otherwise an exception is thrown telling me to annotate classes with
    @Serializable
    but all of them are and work fine on Kotlin/JVM
    r
    • 2
    • 1
  • d

    Dariusz Kuc

    01/17/2021, 6:55 PM
    hello 👋 what is the suggested way to use wrapper objects? i.e. given some
    String
    value I'd like to have it wrapped in
    data class Wrapper(val value: String)
    , in Jackson I can use
    @JsonCreator/@JsonValue
    annotations to achieve this. Based on the docs it looks like I need to build a custom serializer?
    j
    k
    • 3
    • 3
  • w

    william

    01/18/2021, 7:11 PM
    whats the appropriate way to convert a
    Map<String, String>
    into an object that is marked
    @Serializable
    ?
    c
    • 2
    • 1
  • b

    bsimmons

    01/19/2021, 3:50 PM
    Hey all, so I'm storing a
    @Serializable
    class on disk that persists between user sessions. Does anyone here have experience with making sure that new versions of this class are compatible with the old serialized strings? In the case of field name changes, must I keep both versions of the class and manually do the transformations myself whenever a new version of the app is pushed? Any thoughts or ideas are welcome.
    n
    • 2
    • 3
Powered by Linen
Title
b

bsimmons

01/19/2021, 3:50 PM
Hey all, so I'm storing a
@Serializable
class on disk that persists between user sessions. Does anyone here have experience with making sure that new versions of this class are compatible with the old serialized strings? In the case of field name changes, must I keep both versions of the class and manually do the transformations myself whenever a new version of the app is pushed? Any thoughts or ideas are welcome.
n

Nikky

01/20/2021, 12:49 AM
make sure to have default values for new fields.. you can add aliases to fields too if you need to fix it manually you can decode it as a JsonObject, fix it up manully and then parse the fixed JsonObject, write that to disk afterwards you can configure
Json
to ignore unknown fields, for things that are not used at all anymore (and that do nto need to be transformed into other fields)
if you want full control.. i would suggest to have a
version
field, parse your file as a
JsonObject
and then run migration functions on it until it is on the latest version, then you can parse and roundtrip it back to disk
b

bsimmons

01/20/2021, 12:43 PM
Cool. That makes a lot of sense. Thanks for these ideas!
View count: 7