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

    KV

    07/26/2021, 11:45 AM
    Hello,
    const val START_ACTION = "start"
    enum class Actions(val info: String) {
        START(START_ACTION)
    }
    ---------------------------------------------------------------------------
    @Serializable
    data class ActionRequest(
        @SerialName("action_type")
        val actionType: Actions  ----> enum is compulsory to use here
    )
    ---------------------------------------------------------------------------
    val actionRequest = ActionRequest(actionType = START)
    ---------------------------------------------------------------------------```
    Here, I am getting output is "START" rather than "start". Can someone please help me with how to get the value of action here?
    p
    • 2
    • 2
  • e

    eygraber

    07/28/2021, 5:02 AM
    Is there any way to mark a generic type parameter as being serializable? So that I can do something like:
    class Test<T>(val t: T) {
      val serializer = T::class.serializer() // I know this doesn't work
    }
    e
    e
    • 3
    • 18
  • s

    Slackbot

    07/29/2021, 7:36 AM
    This message was deleted.
    d
    • 2
    • 1
  • m

    Matthew Cachia

    08/01/2021, 6:17 AM
    I have the following
    Either<L, R>
    construct which is a third party (and therefore created its own serialiser:
    EitherSerializer
    ). However, deserialising straight to it doesn't work. typealias doesn't work either.
    // yields kotlinx.serialization.SerializationException: Serializer for class 'Either' is not found.
    Json.decodeFromString<Either<SchemaObject, ReferenceObject>>(json)
    
    
    // yields  kotlinx.serialization.SerializationException: Serializer for class 'Either' is not found.
    typealias EitherAlias<L, R> = @Serializable(EitherSerializer::class) Either<L, R>
    ...
    Json.decodeFromString<EitherAlias>(json)
    
    
    // works fine!
    @Serializable
    data class NestedInAClass(val schema: @Serializable(EitherSerializer::class) Either<SchemaObject, ReferenceObject>)
    ...
    Json.decodeFromString<NestedInAClass>(json)
    It looks like it would work only if it is nested within a serialised class. I don't see why typealias wouldn't work. Any help would be appreciated!
    d
    e
    • 3
    • 3
  • a

    ankushg

    08/03/2021, 12:45 AM
    If I have a json string blob like:
    {
      foo: [1, 2, 3]
    }
    Is there a way to deserialize that into
    data class MyClass(val foo: String)
    and have the value of
    MyClass.foo
    be the string
    "[1, 2, 3]"
    ?
    e
    • 2
    • 2
  • w

    Waqas Tahir

    08/03/2021, 4:43 PM
    I need to serialize delegated properties , is there anyway I can work around this !!
    t
    • 2
    • 3
  • w

    Waqas Tahir

    08/04/2021, 6:56 AM
    abstract class MapNode {
    
        // Node Properties
        var isGroup by mutableStateOf(false)
        var colorIndex by mutableStateOf(0)
    
        // Node Children
        @Serializable(with = SnapshotStateListSerializer::class)
        var left = mutableStateListOf<MapNode>()
    
    }
    How can I write a Custom Serializer for this class ?? that serializes all these properties ! (including delegated properties)
    d
    • 2
    • 25
  • b

    Bruno Medeiros

    08/06/2021, 4:34 PM
    Hey, guys. I have an KMM module with many serializable classes generating code for JVM, iOS and JS. I just realized today that my JS bundle (IR) is huge and the main cause is the
    $serializer
    synthetic property that is created for each class/companion. If I remove all my
    @Serializable
    , my module reduce its size by 80%. JVM an iOS are fine, but I can't pay that price in JS. Question is: Is there a way to disable kotlinx-serialization
    $serializer
    generation just in the JS backend? If I could disable it just in JS, I could still use the
    kotlinx-serialization
    serializer for all backends and I'd roll my own for JS, but I would still be able to use my data classes in JS.
    👀 1
    t
    • 2
    • 22
  • m

    Marc Knaup

    08/06/2021, 7:45 PM
    Is it possible to set the “encode defaults” on a per-class or even per-property basis?
    d
    • 2
    • 2
  • a

    altavir

    08/07/2021, 10:45 AM
    Is it possible to create a custom serializer for a field (not the class that has this field) that treats the non-nullable field as absent in some cases? I have a structure that could be empty and I would like for serialization to treat absent value as an empty structure and empty structure as absent.
    d
    • 2
    • 2
  • e

    Emiliano Schiavone

    08/09/2021, 10:41 PM
    Hello, Im using retrofit + koltin serializer and Kotlin Serialization Converter (Jake library). I want to see request and responses on the logcat. I added a convert into retrofit
    private val contentType =  "application/json".toMediaType()
    private val json = Json {
        prettyPrint = true
        ignoreUnknownKeys = true
    }
    
    ..
    
    ..addConverterFactory(json.asConverterFactory(contentType))
    But i cannot see the logs on logcat screen. Any idea how to display it?
    d
    • 2
    • 1
  • j

    johnaqel

    08/11/2021, 1:32 AM
    Are there standard serializers for java.time types i.e LocalTime, LocalDate, Instant, etc..? Does such a thing exist. The idea being that they can be imported into a project so that Kotlinx serialization can serialize java.time types automatically?
    e
    • 2
    • 5
  • g

    Gene Cahill

    08/11/2021, 10:50 PM
    Anyone have a general idea of the iOS app size increase implications using the kotlinx serialization protobuf library? Adding the library to our ios code with 5 very small @Serializable classes has resulted in a 377 Kb increase in app size. Does this sound correct? Is the majority of the cost coming from the library or generated code - and how does with scale when adding significantly more Serializable classes?
    r
    • 2
    • 2
  • w

    Waqas Tahir

    08/12/2021, 2:05 PM
    I created a library that depends on kotlin serialization library but in project I have to specify
    classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    how can I avoid this , my project does not need serialization library , only the dependent library needs it so anyone if uses my library does not need to put classpath like this
    t
    j
    c
    • 4
    • 8
  • c

    christophsturm

    08/13/2021, 11:13 AM
    is there a way to directly deserialize json from a byte array without converting it to a string first?
    d
    • 2
    • 4
  • f

    F0X

    08/13/2021, 11:49 AM
    im trying to do this https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/formats.md#format-specific-types, but with
    List<Byte>
    , so a specific generic type. Is it possible, and if so how?
    e
    • 2
    • 1
  • n

    nschulzke

    08/13/2021, 3:51 PM
    I have an interface for Events that has multiple concrete sealed class implementations, like so:
    // in package com.example.platform
    interface Event
    
    // in package com.example.customer
    @Serializable
    sealed class CustomerEvent : Event {
        object CustomerEvent1
        ...
    }
    
    // in package com.example.supplier
    @Serializable
    sealed class SupplierEvent : Event {
        object SupplierEvent1
        ...
    }
    I would like to be able to serialize/deserialize
    Event
    , but I don't really want to have all the event trees in one package, so using one big
    sealed class
    hierarchy doesn't work well. Does anyone have any idea how to go about registering
    Event
    as polymorphically serializable?
    f
    d
    e
    • 4
    • 11
  • n

    Nikita Khlebushkin

    08/14/2021, 10:35 PM
    Hello! I have some weird error trying to run a Ktor call with a body:
    W/System.err: kotlinx.serialization.SerializationException: Serializer for class 'Companion' is not found.
        Mark the class as @Serializable or provide the serializer explicitly.
    The place I am trying to use:
    try {
                api.createAccount(Account(handle = "some", displayname = "Some name"))
            } catch (e: Exception) {
                e.printStackTrace()
            }
    And the class itself:
    import kotlinx.serialization.Serializable
    
    @Serializable
    data class Account(val handle: String, val displayname: String)
    Ktor's HttpClient config contains:
    install(JsonFeature) {
                serializer = KotlinxSerializer(Json {
                    ignoreUnknownKeys = true
                    encodeDefaults = true
                    useAlternativeNames = false
                })
            }
    In my build.gradle.kts of the module I have:
    plugins {
        kotlin("multiplatform")
        kotlin("plugin.serialization")
        id("com.squareup.sqldelight")
        id("com.android.library")
    }
    
    kotlin {
        ...
        sourceSets {
    
            val serializationVersion = "1.2.2"
            val ktorVersion = "1.6.2"
    
    
            val commonMain by getting {
                dependencies {
                    implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serializationVersion")
                    implementation("io.ktor:ktor-client-core:$ktorVersion")
                    implementation("io.ktor:ktor-client-serialization:$ktorVersion")
                    implementation("io.ktor:ktor-client-logging:$ktorVersion")
                }
            }
            val androidMain by getting {
                dependencies {
                    implementation("io.ktor:ktor-client-okhttp:$ktorVersion")
                }
            }
            val iosMain by getting {
                dependencies {
                    implementation("io.ktor:ktor-client-ios:$ktorVersion")
                }
            }
        }
    }
    What am I doing wrong?
    • 1
    • 1
  • a

    Ayfri

    08/15/2021, 1:23 AM
    Hi, how can I use
    decodeNullableSerializableElement
    on a
    Byte?
    value ? Or in other words, how can I deSerialize a
    Byte?
    ?
    e
    • 2
    • 6
  • a

    Ayfri

    08/15/2021, 4:15 AM
    And how can I make optional deletaged properties ? I'm coupling serialization with Compose and I have a
    val state by mutableStateOf(MyEnum.FIRST_VALUE)
    , I want to omit the field if it is equal to
    MyEnum.FIRST_VALUE
    as it is the default one and most used through my code, but I don't understand how 🤔 I have a custom Serialiazer and I'm encoding the value as Nullable and I've set
    encodeDefaults = false
    in my Json configuration, but it's still emitted and when I try to read the JSON I get this
    Exception in thread "AWT-EventQueue-0" kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 8: Expected numeric literal
    JSON input: [{"task":"test #1","state":null},{"task":"test #2","state":null}]
    e
    • 2
    • 2
  • j

    Jesse Hill

    08/17/2021, 7:23 PM
    What would be the recommended approach to deserialize a JSON structure that has two different keys that represent the same values? Examples are in the thread. Edit: (One possible solution is in the thread, turns out I wasn’t reading the error message correctly 😬)
    d
    • 2
    • 5
  • a

    ankushg

    08/18/2021, 7:14 PM
    2. Is it possible to use a field as a discriminator and also have it in the deserialized object? I.e., we are successfully using
    type
    as the discriminator, but we'd also like to have a
    val type
    inside the deserialized object, containing the same content as
    type
    from the serialization logic. I imagine that the tricky part here would be that there's no guarantees that the
    val type
    would always line up with the class discriminator when serializing or mutating a deserialized class?
    c
    e
    r
    • 4
    • 4
  • a

    Ashley Figueira

    08/19/2021, 10:48 AM
    Hey guys, I am working with an API that either returns a success response or an error response (both HTTP 200). They are 2 different JSON. How would I deserialize this using Kotlinx Serialization and Ktor? Would like to deserialize this into a sealed class like so:
    sealed class ApiResponse {
        data class Success(val fields: String) : ApiResponse()
        data class Error(val errorCode: String, val errorMessage: String): ApiResponse()
    }
    Is there any tutorial on how to do something like this?
    j
    n
    • 3
    • 4
  • a

    altavir

    08/20/2021, 5:01 PM
    I have a complicated problem (as always). I have a large json that could have something like
    { $ref: 2}
    instead of some of its nodes. My task is to find those nodes and replace them by objects those refs are referencing to. The problem is that I do not know in advance on which level those refs will appear. It is quite easy to create either custom decoder o custom serializer that checks specific node and replaced it if it is ref, but I can't see a way to propagate this decoder/serializer logic recursively to sub-nodes. Does anybody have a similar expirience? I know that is is possible to do in @pdvrieze's XML processor by applying custom decoder logic to configuration.
    t
    e
    +2
    • 5
    • 10
  • e

    Emil Kantis

    08/23/2021, 12:56 PM
    Is there any way to write custom literals when defining a
    KSerializer<T>
    ? Use case would be writing a BigDecimal without precision-loss as
    { "myValue": 0.12345 }
    , but without using a Double along the way. Likewise it would be nice to be able to use a
    decoder.decodeUnquotedString
    or something, to parse the above value into a string rather than double without needing to set
    isLenient
    • 1
    • 2
  • t

    Tomas Kormanak

    08/24/2021, 7:54 AM
    Hi, is it possible to make some property not serialized conditionally, based on property value?
    • 1
    • 1
  • e

    Emil Kantis

    08/24/2021, 9:06 AM
    Are there any plans on supporting polymorphic serialization of sealed interfaces?
    d
    p
    c
    • 4
    • 4
  • r

    Richard Gomez

    08/24/2021, 4:04 PM
    How would I go about deserializing a top-level JsonArray (
    ["v1", "v2", "v3"]
    ) as a data class?
    @Serializable
    data class VersionResponse(val versions: List<String>)
    I've made several attempts with
    JsonTransformingSerializer
    , but no dice! 😔
    p
    • 2
    • 6
  • g

    Gene Cahill

    08/25/2021, 10:23 PM
    How can I view the generated code from @Serializable classes in Android Studio?
    e
    • 2
    • 2
  • n

    Nathan Bedell

    08/27/2021, 3:08 PM
    Hey all, I haven't had the chance to make use of kotlinx.serialization yet, but from looking at the docs I'm really excited for it, and it actually reminds me a lot of the rust library serde. One of my hopes, since kotlinx.serialization is implemented via a compiler plugin was that the compiler would be able to warn you at compile-time if you try to serialize a class that isn't serializable. This would resolve one of my major gripes with libraries like GSON: I don't want to have to try to serialize something where the serialization wasn't set up correctly, only to get a cryptic error at run time. Currently, as I understand it reading the docs, this doesn't happen -- and you get a runtime exception instead. Are there any plans currently to support this kind of compile time checking in kotlinx.serialization?
    r
    e
    • 3
    • 5
Powered by Linen
Title
n

Nathan Bedell

08/27/2021, 3:08 PM
Hey all, I haven't had the chance to make use of kotlinx.serialization yet, but from looking at the docs I'm really excited for it, and it actually reminds me a lot of the rust library serde. One of my hopes, since kotlinx.serialization is implemented via a compiler plugin was that the compiler would be able to warn you at compile-time if you try to serialize a class that isn't serializable. This would resolve one of my major gripes with libraries like GSON: I don't want to have to try to serialize something where the serialization wasn't set up correctly, only to get a cryptic error at run time. Currently, as I understand it reading the docs, this doesn't happen -- and you get a runtime exception instead. Are there any plans currently to support this kind of compile time checking in kotlinx.serialization?
r

Richard Gomez

08/27/2021, 3:09 PM
It results in a compile-time error:
[ERROR] Failed to execute goal org.jetbrains.kotlin:kotlin-maven-plugin:1.5.21:compile (compile) on project my-project: Compilation failure
[ERROR] /Users/REDACTED/src/main/kotlin/MyModel.kt:[18,26] Serializer has not been found for type 'MyModel.NonSerializableClass'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
:kotlin-intensifies: 1
It also shows up as a warning in IntelliJ
e

ephemient

08/27/2021, 4:55 PM
there are reflection-based apis in kotlinx.serialization - e.g.
Json.encodeToString(value)
-versus non-reflective
Json.encodeToString(serializer(), value)
also
@Contextual
,
@Polymorphic
may fail at runtime if you didn't register the types in the serializers module
but otherwise serialization issues should be caught at compile time
View count: 7