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

    Carter

    05/16/2021, 5:35 PM
    Firestore still isn’t convenient most of the time anyway, because all the fields have to be a
    var
    and
    ?
    . For all my Firestore data, I ended up creating
    Model
    for an immutable and non-null representation and a parallel
    CloudModel
    with mutable and nullable representation for automatic Firestore serialization. I added companion functions to convert between the two, and that deals with specific differences (e.g. date representations). It means some extra code, but it also means that Firebase limitations don’t propagate through my codebase and I get to be explicit about the conversion. That’s the solution I ended up with, although I’d be curious if other good patterns have emerged.
    s
    • 2
    • 1
  • g

    Gilles Barbier

    05/16/2021, 8:54 PM
    Hello, can serialization 1.2+ be used with kotlin 1.4+ ?
    n
    s
    • 3
    • 3
  • d

    Daniele B

    05/17/2021, 8:38 AM
    instead of Json format:
    val obj = Json.decodeFromString<Data>("""{"a":42, "b": "str"}""")
    is there a way to decode key/value pairs concatenated by
    &
    ?
    a=42&b=str
    or should I convert my key/value pairs into Json?
    e
    d
    • 3
    • 6
  • d

    Daniele B

    05/17/2021, 12:05 PM
    Is there any way/trick to enforce that classes implementing a specific interface should always be annotated as
    @Serializable
    ?
    interface ScreenParams
    
    @Serializable
    data class CountriesListParams(val listType: CountriesListType) : ScreenParams
    
    @Serializable
    data class CountryDetailParams(val countryName: String) : ScreenParams
    all these 3 definitions are on different files, so it can happen to forget to set
    @Serializable
    If the annotation is forgotten, the app would crash at runtime when visiting that specific screen.
    s
    • 2
    • 2
  • r

    ribesg

    05/18/2021, 9:58 AM
    I’m still blocked by this using kotlinx.serialization 1.2.1
    • 1
    • 1
  • h

    huehnerlady

    05/18/2021, 2:32 PM
    Hi, I currently try to generate a json schema from kotlin classes and generating kotlin classes from json schema. For my first part - creating schema from kotlin classes, I ran into this post on stack overflow and there I was pointed to kotlinx.serialization at a very early stage (see here). unfortunately this folder was completely removed in this commit. Now I cannot find any hint of similar classes or how I could achieve just that. Is this still possible with kotlinx.serialization? If so — how? If not — any other idea how I can achieve that?
    n
    d
    • 3
    • 12
  • d

    Dariusz Kuc

    05/20/2021, 4:00 AM
    Hello 👋 How can we define optional nullable fields so we can distinguish following cases during serialization 1) omitted value 2) explicit
    null
    3) value set I used a sealed class and custom Jackson deserializer in the past (link) but now I'm looking into serialization and need to support
    kotlinx-serialization
    . I tried something using custom serializer and "skipping" the encode part when I process an instance of
    Undefined
    sealed class but that produces me a broken JSON, e.g. given
    data class Wrapper(val name: OptionalInput<String>)
    I end up with
    { "name": }
    . Any ideas? I don't see any option to skip element in the
    JsonEncoder
    c
    k
    j
    • 4
    • 7
  • d

    Denys

    05/20/2021, 6:05 PM
    Help me please. I am trying to update kotlin to version “1.5.0” and kotlinx-serialization-json to version “1.2.0" . After the update, the project stopped building - “java.util.NoSuchElementException: Collection contains no element matching the predicate.     at org.jetbrains.kotlinx.serialization.compiler.backend.ir.IrBuilderExtension$DefaultImpls.serializableSyntheticConstructor(GeneratorHelpers.kt:1255)”
    t
    • 2
    • 3
  • i

    Ivan Đorđević

    05/21/2021, 8:36 AM
    Are serial descriptors generated by the compiler plugin mutable?
    b
    • 2
    • 1
  • n

    natario1

    05/21/2021, 5:01 PM
    Trying to transform a
    class Sms(val phone: String, val code: String)
    into
    {"sms":{"phone":"1230129","code":"23984"}}
    ... I know that I can add
    SmsWrapper(val sms: Sms)
    and require people to use it, but I'd like to use a custom serializer instead. Is there any example to do such thing? I see many examples where structures are flattened (e.g. you remove a
    {}
    container), but couldn't find one where you do the opposite (nest data in a new
    {}
    ).
    b
    d
    • 3
    • 3
  • m

    marzelwidmer

    05/24/2021, 12:26 PM
    Hello have somebody any elegant solution vor validation I saw the following
    feature
    is still open 🙂 https://github.com/Kotlin/kotlinx.serialization/issues/318 for https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#data-validation
    t
    d
    n
    • 4
    • 14
  • s

    Sam

    05/25/2021, 10:43 AM
    Hello, good evening everyone. I have a plan replace Gson to Serialization. But My project has many modules, they are using Moshi and Gson in Core module ( base module for all of Features) So What are the pros and cons of using Serialization library? Is there anything I need to keep in mind when switching from Gson to Serialization? Thanks.
    b
    d
    c
    • 4
    • 5
  • z

    zeugederunity

    05/25/2021, 12:47 PM
    Hello everyone, after upgrading to Kotlin 1.5.10 with kotlinx-serialization-Version 1.2.0 (from Kotlin 1.4.30 and kotlinx-serialization 1.0.1) my code throws the following error:
    java.lang.IllegalStateException: Class Instant have constructor parameters which are not properties and therefore it is not serializable automatically
    	at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializerCodegen.checkSerializability(SerializerCodegen.kt:28)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializerCodegen.generateSerializableClassPropertyIfNeeded(SerializerCodegen.kt:101)
    	at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializerCodegen.generate(SerializerCodegen.kt:34)
    I allready created a minimal Example at: https://github.com/FelixEngl/FailingInstantSerialisation Does anyone know how to fix this?
    r
    • 2
    • 4
  • u

    ushort

    05/25/2021, 5:51 PM
    Hello, was wondering if anyone can help me understand how a custom decoder should handle maps? Specifically how it might be handled inside decodeElementIndex. I'm having trouble with writing decoder that handles map<string, object>. What currently happens is it decodes one of the map keys, then it switches to class structure and after decoding the class members, it continues to decode the class members of the other key instead of ending the structure and restarting?
    r
    b
    • 3
    • 3
  • t

    tseisel

    05/27/2021, 6:35 PM
    I need to deserialize 2 versions of an entity
    Entity
    : one with all properties, and another
    SimpleEntity
    with only the most used properties from
    Entity
    . How can I do that? I thought of using closed polymorphism but I can't use a discriminator because I don't control the input JSON.
    d
    • 2
    • 5
  • g

    Goth

    05/28/2021, 1:41 AM
    1. this should deserilize to Message<SimmplePayload>
    { 
      id = "1",
      type = "simple",
      payload =  {
        name = "Blah"
      }
    }
    
    
    2. this should deserilize to Message<AdvancedPayload>
    { 
      id = "2",
      type = "advanced",
      payload =  {
        name = "WOW",
        description = "WOW WOW"
      }
    }
    r
    d
    • 3
    • 10
  • l

    LastExceed

    05/29/2021, 7:04 PM
    this jb blog post says
    The default serializer is based on an ISO 8601 string representation of a type and uses `toString()`/`parse()` to serialize and deserialize values
    the linked wikipedia article lists
    2021-05-29T17:42:42+00:00
    as an example string so why do i get an exception here ?
    -.cpp
    e
    • 2
    • 4
  • j

    Julián Falcionelli

    05/30/2021, 11:08 AM
    Hi guys, I am facing a serialization issue when using Kotlinx serialization with a Firebase Library in a KMM project. I have the following hierarchy classes that I want to persist in Firebase Realtime Databases.
    @Serializable
    sealed class Activity {
      abstract val type: Type
    
      @Serializable
      enum class Type(
        val enabled: Boolean,
        @Transient
        val shortName: StringResource
      ) {
        BJJ(
          true,
          MR.strings.activity_bjj,
        ),
        GRAPPLING(
          true,
          MR.strings.activity_grappling,
        )
      }
    
      @Serializable
      data class Bjj(
        override val type: Type = Type.BJJ,
        var belt: Belt? = null,
        val stripes: Int = 0
      ) : Activity() {
        @Serializable
        enum class Belt(
          @Transient
          val color: ColorResource.Single
        ) {
          WHITE(MR.colors.belt_white),
          BLUE(MR.colors.belt_blue),
          PURPLE(MR.colors.belt_purple),
          BROWN(MR.colors.belt_brown),
          BLACK(MR.colors.belt_black)
        }
      }
    
      @Serializable
      data class Grappling(
        override val type: Type = Type.GRAPPLING
      ) : Activity()
    }
    I actually send it as a List, something like this: // Firebase Call
    val ref = database
      .child(ROOT_PATH)
      .child(user.id)
      .child("activities")
    ref.setValue(ListSerializer(Activity.serializer()), updatedActivities)
    Seems that the Firebase Library doesn’t support auto-serialization of sealed classes and I am not sure how to solve this problem.  
    java.lang.ClassCastException: kotlinx.serialization.descriptors.PolymorphicKind$SEALED cannot be cast to kotlinx.serialization.descriptors.StructureKind
        
    at dev.gitlive.firebase._encodersKt.structureEncoder(_encoders.kt:12)
    n
    s
    • 3
    • 4
  • s

    Spikey Sanju

    06/02/2021, 8:30 AM
    Hello all, I’m getting error when I try deserialize an object from JSON using Kotlin Serialization. I get the following error 👇
    j
    v
    • 3
    • 5
  • s

    Spikey Sanju

    06/03/2021, 10:17 AM
    Hello all, Kotlin Serialization works fine for
    small chunk of JSON data
    . But when I try to
    deserialize
    the
    large JSON file
    . It’s throwing me this weird issue. Why is it happening? P.S - I
    validated the JSON
    . And there’s no issue with it ✅
    Kotlin Serialization Issue.mov
    s
    • 2
    • 2
  • p

    pniederw

    06/06/2021, 3:48 PM
    Is or will it be possible to write a serializer for
    Map<String, (Number|Boolean|String)?>
    , ideally in a serialization format agnostic way? I guess what I'm asking for is
    Decoder.peekType()
    . I've looked at
    JsonDecoder.decodeJsonElement()
    but the implementation is all
    internal
    .
    e
    n
    • 3
    • 24
  • l

    LastExceed

    06/08/2021, 8:44 AM
    i want a
    class AA
    with a property
    x: Int
    and a
    class BB
    with properties
    x: Int
    and
    y: Int
    where
    BB
    inherits from
    AA
    (alternative: inner class would be ok too in case thats the only option) i've tried the snippets below, but no success so far. i checked the guide but couldnt find what i need. how do i make this work?
    Untitled_kt.cpp
    a
    • 2
    • 3
  • s

    Sourabh Rawat

    06/09/2021, 11:33 AM
    How can I register serializers for my custom Json object? I prefer not to specify serialisers all the time when calling
    encodeToString
    e
    • 2
    • 4
  • l

    LastExceed

    06/11/2021, 6:03 AM
    can someone explain what i need to put into that string? the docs say
    a unique name of the type that is being serialized
    but i dont understand what that means also why does Line 2 work but Line 3 break ?
    Untitled.cpp
    e
    • 2
    • 30
  • c

    CLOVIS

    06/11/2021, 10:52 AM
    If I add a primary constructor (
    init
    block) to a serialized data class, will it be executed on deserialization?
    :yes: 1
    • 1
    • 2
  • c

    CLOVIS

    06/12/2021, 12:55 PM
    Are they known bugs with sealed classes in 1.2.1 in JS/JVM?
    val data: Data
    where
    Data
    is a sealed class gives me
    "data": {
    	"type": "SIMPLE",
    	"id": "TEXT"
    }
    on JS, and
    "data": [
    	"SIMPLE",
    	{
    		"id": "TEXT"
    	}
    ]
    on JVM, which unsurprisingly completely fails when Ktor tries to send messages between them.
    d
    j
    • 3
    • 9
  • s

    Sourabh Rawat

    06/12/2021, 1:34 PM
    How can I handle extra fields when deserialising? For example, I have -
    class Foo(val bar: String)
    in. json I have
    { bar: 'asd', foobar: 'jkl', fb1: 'abc'}
    I want to deserialise the above json into class Foo, but also be. able to access
    foobar & fb1
    , somehow. without having to add those fields in class Foo specifically. What I am looking for is something like
    extraFields
    map
    n
    • 2
    • 1
  • n

    Nikky

    06/14/2021, 12:23 PM
    seems like there is some weirdness with deeply nested arrays on jvm
    [[Ljava.lang.Object; cannot be cast to [[[D
    it works fine on js or when downgrading to serialization
    1.0.1
    tthe affected types / typealiases are
    typealias PointCoordinates = DoubleArray
    typealias MultiPointCoordinates = Array<PointCoordinates>
    typealias LineStringCoordinates = Array<PointCoordinates>
    typealias LinearRingCoordinates = Array<PointCoordinates>
    typealias MultiLineStringCoordinates = Array<LineStringCoordinates> // Outer polygon + holes
    typealias PolygonCoordinates = Array<LinearRingCoordinates> // Outer polygon + holes
    typealias MultiPolygonCoordinates = Array<PolygonCoordinates>
    it is for geojson out of the typeliases
    PolygonCoordinates
    and
    MultiPolygonCoordinates
    seem to be affected
    • 1
    • 1
  • n

    Nikolay Kasyanov

    06/14/2021, 2:11 PM
    Hey folks 👋 while deserializing (implementing
    KSerializer.deserialize
    ), is there a way to get access to the “raw” value of a primitive? As a string, for example. Since JSON numbers don’t have to be floating point numbers (by the standard https://www.json.org/json-en.html, although some implementation do assume that they are all double, unfortunately), I need a way to read fractional numbers from JSON without compromising their precision (to convert them to some decimal type, for example), none of the existing
    Decoder
    can do that it seems. Am I missing something? One option would be to write such values as strings server-side, but 1) it’s not always feasible to change existing endpoints that are just fine 2) one doesn’t always control the API. UPD found an issue, apparently it’s not possible atm: https://github.com/Kotlin/kotlinx.serialization/issues/1405
    • 1
    • 2
  • j

    Jason Ankers

    06/14/2021, 3:42 PM
    Is serializing anonymous objects supported in kotlinx serialization? something like:
    @Serializable object {
        val message = "some message"
    }
    b
    e
    • 3
    • 9
Powered by Linen
Title
j

Jason Ankers

06/14/2021, 3:42 PM
Is serializing anonymous objects supported in kotlinx serialization? something like:
@Serializable object {
    val message = "some message"
}
Seems to throw an internal error
e: java.lang.IllegalStateException: not identifier: <no name provided>
	at org.jetbrains.kotlin.name.Name.getIdentifier(Name.java:39)
	at org.jetbrains.kotlin.cli.jvm.index.JvmDependenciesIndexImpl.search(JvmDependenciesIndexImpl.kt:115)
	at org.jetbrains.kotlin.cli.jvm.index.JvmDependenciesIndexImpl.traverseDirectoriesInPackage(JvmDependenciesIndexImpl.kt:77)
	at org.jetbrains.kotlin.cli.jvm.index.JvmDependenciesDynamicCompoundIndex.traverseDirectoriesInPackage(JvmDependenciesDynamicCompoundIndex.kt:59)
	at org.jetbrains.kotlin.cli.jvm.index.JvmDependenciesIndex$DefaultImpls.traverseDirectoriesInPackage$default(JvmDependenciesIndex.kt:33)
	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinCliJavaFileManagerImpl.findPackage(KotlinCliJavaFileManagerImpl.kt:191)
b

bsimmons

06/14/2021, 4:12 PM
Yeah, if you look at most of the serializable functions from the library, they require specific type parameters. So yeah, this wouldn't make sense for an anonymous object
e

ephemient

06/14/2021, 4:14 PM
how would it be deserialized?
j

Jason Ankers

06/14/2021, 5:40 PM
Presumably the same way it would be deserialized if it were an explicit type
b

bsimmons

06/14/2021, 5:51 PM
^^ I think that was a rhetorical question.
😉
j

Jason Ankers

06/14/2021, 6:05 PM
Why would it be rhetorical lol
e

ephemient

06/14/2021, 6:17 PM
serious question, in terms of "have you thought through everything that's involved"
@Serializable
generates a KSerializer that performs both serialization and deserialization. the descriptor here needs to have a SerialName (even if you don't use it, because some formats do), the object here also does not have a constructor that a deserializer can invoke, and it definitely can't work if it captures anything
👍 1
View count: 13