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

    Matej Drobnič

    07/28/2019, 6:58 PM
    Is there a more elegant way to solve
    ImplicitReflectionSerializer
    ? I want to create generic method to send data classes through Websocket. At the moment I have this:
    suspend fun <T> send(item: T, serializer: KSerializer<T>) {
        // TODO
    }
    but it is a bit awkward to always pass the serializer. Since I'm always sending data classes which do not support extension, runtime type is not important to me, I would be fine with just detecting the compile-time type.
    s
    • 2
    • 1
  • d

    Dominaezzz

    07/29/2019, 6:29 AM
    Is partial deserialisation supported? I have a Json object where I know some fields will be there and others may not but I don't know what they are called at compile time. Can the plugin shove all the unknown keys into a
    JsonObject
    member?
    🇳🇴 1
    s
    • 2
    • 3
  • d

    Dominaezzz

    07/29/2019, 9:14 AM
    I have
    data class Request(val mode: String = "default", val extra: String? = null)
    , this produces
    { "mode": "default", "extra": null }
    . Can I get it to omit the field entirely instead of setting it to
    null
    ?
    g
    • 2
    • 3
  • d

    Dominaezzz

    07/29/2019, 11:46 PM
    Is having a
    classDiscriminator
    per parent class planned?
    s
    • 2
    • 7
  • s

    sandwwraith

    07/30/2019, 8:21 AM
    I've updated documentation with an article about polymorphic serialization, hope it will answer some of your questions: https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md
    🎉 9
    s
    a
    • 3
    • 5
  • s

    sandwwraith

    07/30/2019, 8:57 PM
    Seems that idea of having different `classDiscriminator`s per one response is really popular. We'll take a look on how we can implement this.
    👍 9
    s
    m
    d
    • 4
    • 8
  • s

    Sam

    08/01/2019, 6:51 PM
    I'm trying to serialize a tree of expressions that must match a format that will be sent to an api. The expressions are a set of sealed classes that may or may not contain other expression classes. For instance the root is always an expression class that contains a list of other expression object as one of it's properties. Each node in the tree has it's own discriminator property called type. Right now I don't need to deserialize this json but I may need to in the future. The important part is that my output match the api. An example looks like:
    {
      "type": "V",
      "expressions": [
        {
          "type": "M",
          "expr": "5+6"
        }
      ],
      "resultType": "success"
    }
    I started to go down the route of using the polymorphic serializer but I didn't know how to customize the
    type
    output. Should I write my own custom serializer for this type? If so is there a good example of how to do this?
    d
    • 2
    • 5
  • s

    Soren Valle

    08/01/2019, 9:43 PM
    Learning kotlin/react/redux. Redux doesn't like a "preloadedState" to be anything other than a plain js object. Sending back an initialized data class makes it complain about expecting an object, not and "Object". This is the best I could figure, is there a better way that I'm missing?
    package index.store.state
    
    import index.model.User
    import kotlinx.serialization.Serializable
    import kotlinx.serialization.json.Json
    import kotlinx.serialization.json.JsonConfiguration
    
    @Serializable
    data class State(val users: Array<User> = emptyArray())
    
    fun state(): State {
    
        val json = Json(JsonConfiguration.Stable)
    
        return JSON.parse(
            json.stringify(
                State.serializer(),
                State()
            )
        )
    }
    It feels cleanish, but it seems like there might/should(?) be a native function I can't find that converts a data class to a kotlin.js.Json object.
    t
    • 2
    • 16
  • d

    Dominaezzz

    08/02/2019, 10:04 AM
    How does one create a
    Json
    without treading experimental?
    f
    • 2
    • 2
  • j

    jw

    08/02/2019, 6:37 PM
    it does not offer CSV as a built-in serialization target but the plugin is agnostic to formats meaning you are able to support CSV yourself
    f
    g
    • 3
    • 4
  • s

    serebit

    08/03/2019, 1:10 AM
    kotlinx.serialization 0.11.1 seems to be published with incorrect Gradle metadata. I have a dependency on the
    kotlinx-serialization-runtime-native
    artifact in my project's
    commonMain
    source set, and with Gradle metadata enabled, this propagates to all the source sets (including JVM). That project's build succeeds, but if I publish the project to Maven and attempt to depend on it from another (JVM) project, running the other project fails with the error
    Exception in thread "main" java.lang.NoClassDefFoundError: kotlinx/serialization/SerializationStrategy
    . If I add a manual implementation dependency on the runtime in the second project, this error goes away.
    ❓ 3
    d
    • 2
    • 1
  • k

    kevin.cianfarini

    08/06/2019, 2:49 AM
    Has anyone seen this error before?
    Caused by: kotlinx.serialization.SerializationException: Can't locate argument-less serializer for class com.kevincianfarini.saddle.Artist$Impl (Kotlin reflection is not available). For generic classes, such as lists, please provide serializer explicitly.
    I've done some searching but none of the solutions I've found have worked.
    i
    m
    • 3
    • 16
  • f

    Fudge

    08/06/2019, 9:34 AM
    While making a custom encoder/decoder, it is possible to support additional data formats so that users don't need to do
    @Serializable(with = ...::class)
    whenever they use the data format? For example, support UUID:
    class MyEncoder : NamedValueEncoder {
         fun encodeInt() { ... }
          ...
         fun encodeUUID() { ... }
    }
    class MyDecoder : NamedValueDecoder {
          fun decodeInt() { ... }
           ...
          fun decodeUUID() { ... }
    And then users can do:
    @Serializable
    data class OtherFormats(val uuid: UUID)
    Instead of:
    @Serializable
    data class OtherFormats(@Serializable(with = UuidSerializer::class) val uuid: UUID)
    (where
    UuidSerializer
    is the name of a class annotated with
    @Serializer(forClass=UUID::class)
    )
    d
    • 2
    • 3
  • j

    Jeremy

    08/07/2019, 2:45 AM
    https://gist.github.com/jeremyrempel/ff5821bd099104ea5358a987f32105f1
    r
    • 2
    • 7
  • r

    ross_a

    08/07/2019, 9:17 PM
    Turns out it's this combination of annotations that makes it choke:
    @ExperimentalUnsignedTypes
    @FlowPreview
    @ObsoleteCoroutinesApi
    @ExperimentalCoroutinesApi
    l
    • 2
    • 1
  • s

    Sergioedcigreja

    08/08/2019, 9:53 AM
    Hey guys, I have a Json which can have a certain key that varies in name but I cant seem to find out how to do this.. any ideas? I really just need the value inside it..
    d
    • 2
    • 7
  • t

    thana

    08/08/2019, 1:25 PM
    with kotlin 1.3.41 and serialization 0.11.1 gradle says that it can't find kotlinx . any idea whats going wrong?
    f
    v
    +2
    • 5
    • 26
  • s

    Sam

    08/08/2019, 7:14 PM
    I'm consuming an api that uses an empty string for a null but sends an object when the key is not null like so:
    "mods":{"mod1":""}
    "mods":{"mod1":{"comp":">=","point":3}}
    Is there a way to construct a class or annotate the property to deal with this?
    d
    • 2
    • 4
  • m

    Marc Dietrichstein

    08/10/2019, 8:29 AM
    Hey everyone. I am trying to define an external serializer for a data class (
    Data
    ) which is defined in another gradle module (subproject) and the result is the following exception:
    Caused by: java.lang.IllegalStateException: Class Data 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:38)
            at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializerCodegen.generateSerializableClassPropertyIfNeeded(SerializerCodegen.kt:106)
            at org.jetbrains.kotlinx.serialization.compiler.backend.common.SerializerCodegen.generate(SerializerCodegen.kt:44)
            at org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializerCodegenImpl$Companion.generateSerializerExtensions(SerializerCodegenImpl.kt:49)
            at org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationCodegenExtension.generateClassSyntheticParts(SerializationCodegenExtension.kt:30)
            at org.jetbrains.kotlin.codegen.ImplementationBodyCodegen.generateSyntheticPartsAfterBody(ImplementationBodyCodegen.java:438)
            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.PackageCodegenImpl.generateClassesAndObjectsInFile(PackageCodegenImpl.java:118)
            at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generateFile(PackageCodegenImpl.java:137)
            at org.jetbrains.kotlin.codegen.PackageCodegenImpl.generate(PackageCodegenImpl.java:68)
            ... 44 more
    Everything works if the data class is defined in the same gradle module as the serializer though. Has anyone here experienced this as well?
    f
    d
    • 3
    • 5
  • s

    Slackbot

    08/10/2019, 1:17 PM
    This message was deleted.
    f
    • 2
    • 1
  • f

    Fudge

    08/11/2019, 9:36 AM
    Is there an
    ArraySerializer
    ? For primitives like
    ByteArray
    n
    • 2
    • 1
  • f

    Fudge

    08/11/2019, 11:26 AM
    How can a custom format support polymorphic serialization by accepting a
    SerialModule
    ? I can't find where
    Json
    and other formats handle the
    SerialModule
    .
    d
    • 2
    • 2
  • s

    Sergioedcigreja

    08/12/2019, 9:08 AM
    Good Morning guys I'm getting JsonParsingException: Invalid JSON at 55: Expected string or non-null literal while parsing a json that has a field called data which can be null but it could also be a json-object with varying keys. So my idea was to parse it to a String but it seems that that is what's causing the issue. Any ideas on how to accomplish this?
    m
    • 2
    • 1
  • f

    Fudge

    08/13/2019, 10:07 AM
    I'm looking for a way to serialize a specific class using a specific method in my
    NamedValueEncoder
    /
    NamedValueDecoder
    .
    class MyClass {
       /**  **/
    }
    Doing that in a
    ElementValueEncoder
    is simple enough :
    class MyEncoder : ElementValueEncoder(){
        fun encodeMyClass(obj : MyClass){
             /** **/
         } 
    }
    // And then in serializer...
    @Serializer(forClass = MyClass)
    object MyClassSerializer : KSerializer<MyClass> {
          override fun serialize(encoder: Encoder, obj: MyClass) {
            if(encoder is MyEncoder){
                encoder.encodeMyClass(obj)
            }
            else error("not supported")
        }  
    }
    However, I cannot see how I can do the same thing in a
    NamedValueEncoder
    , as it requires a tag, which I don't know how to generate.
    class MyTaggedEncoder : NamedValueEncoder(){
        fun encodeTaggedMyClass(tag: String, obj : MyClass){
             /** **/
         } 
    }
    // And then in serializer...
    @Serializer(forClass = MyClass)
    object MyClassSerializer : KSerializer<MyClass> {
          override fun serialize(encoder: Encoder, obj: MyClass) {
            if(encoder is MyTaggedEncoder){
                encoder.TaggedMyClass( ??????,      obj)
            }
            else error("not supported")
        }  
    }
    I don't have access to the methods that generate the tag, to be used in the area marked as "?????", as they are private in
    NamedValueEncoder
    . There are also no methods that allow
    Any
    class to be encoded in
    NamedValueEncoder
    (of which I don't need to provide a tag myself to) . So how can I encode / decode a tagged
    MyClass
    in this situtation?
    s
    • 2
    • 2
  • l

    leandro

    08/14/2019, 1:27 PM
    I have two types, one a subclass of the other, and I’m trying to make it work with the serialization library:
    @Serializable
    open class Foo(open val foo: String)
    
    @Serializable
    data class Bar(override val foo: String, val bar: String) : Foo(foo)
    The compiler is pointing on
    Bar
    that I have
    foo
    declared twice (
    has duplicate serial name of property foo, either in it or its parents
    ). I could not find this scenario on the polymorphism doc. Does anyone know how to get around this?
    f
    • 2
    • 3
  • a

    altavir

    08/16/2019, 1:35 PM
    I've got a
    MutableMap<Name, @Polymorphic T>
    field, where
    Name
    is an inline class. I have custom serializer for name. Is it possible to somehow implement a serializer for the map inheriting polymorphic behavior?
    d
    s
    • 3
    • 19
  • f

    Fudge

    08/19/2019, 10:37 AM
    How can I support default values in my addon-format? How can I 'tell' the deserializer "here, this value doesn't exist, use the default value instead"
    s
    • 2
    • 9
  • a

    ankushg

    08/21/2019, 2:20 AM
    Maybe a dumb question. I've got a
    data class MyClass(val foo: String)
    that I can conveniently retrive from dynamic JS by using
    DynamicObjectParser().parse(js("""{ foo: "bar" }"""), MyClass.serializer())
    . Is there a way that I can do the opposite, going from an instance of
    MyClass
    to a dynamic type JS blob
    { foo: "bar" }
    ? The goal is to be able to call into the Kotlin/JS artifact from real-JS and be able to predictably interact with the output without having extra bits of data on it. I can get to a
    Map<String, Any?>
    using
    Mapper.mapNullable(MyClass.serializer(), instance)
    , but I'm not sure if there's a step that I'm missing after that...
    f
    • 2
    • 2
  • a

    ankushg

    08/21/2019, 10:21 PM
    Alternatively is this something that I could write some sort of general-purpose
    AbstractSerialFormat
    implementation for?
    f
    • 2
    • 5
  • f

    Fudge

    08/22/2019, 7:03 PM
    Sometimes I get a
    kotlinx.serialization.UpdateNotSupportedException: Update is not supported for <class>
    exception for custom serializers. This only seems to happen when there are multiple objects which have custom serializers in one serializable class, rather than being related to a specific serializer. I guess I could override
    patch
    in all of my serializers, but what is the meaning of
    Update
    and
    patch
    ? Also I feel like I'm not supposed to do this considering the documentation doesn't say to override
    patch
    ...
    • 1
    • 2
Powered by Linen
Title
f

Fudge

08/22/2019, 7:03 PM
Sometimes I get a
kotlinx.serialization.UpdateNotSupportedException: Update is not supported for <class>
exception for custom serializers. This only seems to happen when there are multiple objects which have custom serializers in one serializable class, rather than being related to a specific serializer. I guess I could override
patch
in all of my serializers, but what is the meaning of
Update
and
patch
? Also I feel like I'm not supposed to do this considering the documentation doesn't say to override
patch
...
If I try to use the json serializer I get
java.lang.IllegalStateException: Reader has not consumed the whole input:
very weird
Apparently it was a result of forgetting to call
endStructure
...
View count: 6