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

    edenman

    08/19/2020, 3:08 AM
    if anybody else is using
    KClass.serializer()
    it’s marked as
    @InternalSerializationApi
    in 1.0.0-RC, I filed https://github.com/Kotlin/kotlinx.serialization/issues/991 to try and get some more clarity on why it’s not recommended
    e
    v
    • 3
    • 5
  • r

    rrva

    08/19/2020, 12:38 PM
    ah, depending on ktor 1.4.0 resolved my issue
    a
    • 2
    • 2
  • r

    rrva

    08/19/2020, 1:27 PM
    Is there any more compact way of configuring JSon with these settings
    serializer = KotlinxSerializer(
                    Json {
                        isLenient = true
                        ignoreUnknownKeys = true
                        useArrayPolymorphism = true
                    }
                )
    t
    l
    • 3
    • 3
  • t

    tylerwilson

    08/19/2020, 3:50 PM
    I had some code like this in a custom serializer (found elsewhere) that worked in 0.20.0:
    return when (val jsonElement = JsonElementSerializer.deserialize(decoder)) {
                is JsonArray -> jsonElement.content.map { parser.decodeFromString(dataSerializer, it.toString()) }
                else -> listOf(parser.decodeFromString(dataSerializer, jsonElement.toString()))
            }
    but in 1.0.0-RC the JsonElementSerializer is not recognized. What is the replacement for this?
    v
    • 2
    • 4
  • t

    tylerwilson

    08/19/2020, 4:54 PM
    So my project builds and runs well with Kotlin 1.4.0, but Android Studio shows all serializers like so: anything I can do to fix it?
    l
    • 2
    • 2
  • l

    Luoqiaoyou

    08/20/2020, 4:16 AM
    In Java, we can add/remove property in JSONObject. In serialization, JsonObject is Map that can not be change. Is any suggestion to migrate this logic?
    n
    • 2
    • 5
  • n

    Nikolay Kasyanov

    08/20/2020, 2:11 PM
    Hey folks, reading https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md now, I wonder if I can use a composite key (multiple json fields that is) instead of
    type
    to deserialize subclasses?
    v
    • 2
    • 3
  • v

    Vampire

    08/22/2020, 7:31 PM
    If a field can either be a
    String
    or a
    List<String>
    in the serialized format, can this somehow be catered for with
    kotlinx.serialization
    ? In my concrete case I try using
    kaml
    to parse a GitHub workflow yml file. It can for example have this:
    jobs:
      job1:
      job2:
        needs: job1
      job3:
        needs: [job1, job2]
    n
    v
    • 3
    • 7
  • o

    Ovsyannikov Alexey

    08/23/2020, 6:44 PM
    Hello. I am owner of TelegramBotAPI library and currently I am working on a new update related to new Kotlin and other dependencies versions. I have faced with an issue after upgrade of my project up to Kotlin 1.4.0 and Serialization up to 1.0.0-RC. It is look like currently code for JS serializer is generating incorrectly due to the fact that the test which normally must correctly work is failing. I have created a small bot for that and found the things you will see in attached screenshot. In two words:
    tmp0_subject
    was set up from
    this._file_3
    on line 98291 on screenshot. This value is absent, but there is value
    value._file_3
    which is look like something what must be on place of
    tmp0_subject
    b
    v
    • 3
    • 6
  • v

    Vampire

    08/25/2020, 12:01 PM
    Is there a way / trick / lib to make kotlinx.serializable able to serialize / deserialize simple PoJo trees? With Jackson you can simply do
    ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(it, this)
    and
    ObjectMapper().readValue(buildSrcResultFile, Result::class.java)!!
    . Exists something similar that works with kotlinx.serialization?
    t
    • 2
    • 2
  • m

    Manuel Dossinger

    08/25/2020, 12:13 PM
    Hi everyone. I am trying to serialize a class where a part is implemented by another class using the delegation pattern. Minimal example:
    interface WithValue { val x: Int }
    
    @Serializable
    data class WithValueImpl(override val x: Int) : WithValue
    
    @Serializable
    data class MyClass(val y: Int) : WithValue by WithValueImpl(1)
    
    fun main() {
        println(Json.encodeToString(MyClass(5)))
        // prints: {"y":5}
    }
    In the documentation, I have only found that delegated properties are transient, but nothing regarding delegated interfaces. The desired result would be, that MyClass is encoded as
    {"y": 5, "x": 1}
    . Do you have any pointers for me?
    t
    r
    • 3
    • 5
  • v

    Vampire

    08/25/2020, 1:14 PM
    What am I doing wrong in the following snippet? Important: The answer is not that I do not simply annotate with
    @Serializable
    .
    Foo
    in reality is a Groovy object from a library so it is not modifiable.
    data class Foo(val count: Int = 1)
    
    @Serializer(forClass = Foo::class)
    object FooSerializer : KSerializer<Foo> {
        override val descriptor = SerialDescriptor("Foo") {
            element("count", Int.serializer().descriptor)
        }
    
        override fun deserialize(decoder: Decoder) = decoder.decodeStructure(descriptor) {
            Foo(decodeIntElement(descriptor, 0))
        }
    
        override fun serialize(encoder: Encoder, value: Foo) {
            encoder.encodeStructure(descriptor) {
                encodeIntElement(descriptor, 0, value.count)
            }
        }
    }
    
    println(Json(Stable).parse(FooSerializer, Json(Stable).stringify(FooSerializer, Foo())))
    Result:
    Unexpected JSON token at offset 14: Failed to parse 'int'.
       JSON input: {
          "count": 1
      }
    Because it tries to parse
    count
    as
    Int
    instead of
    1
    :-/
    • 1
    • 1
  • c

    CLOVIS

    08/25/2020, 1:34 PM
    Hi! I'm currently updating a multiplatform project to Kotlin 1.4. I changed the following:
    plugins {
        kotlin("multiplatform") version "1.4.0" // previously 1.3.61
        kotlin("plugin.serialization") version "1.4.0" // same
    }
    and:
    val serialization_version = "1.0.0-RC"
    val commonMain by getting {
        dependencies {
            implementation(kotlin("stdlib-common"))
            implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:$serialization_version")
            // ktor...
        }
    }
    // other targets, with serialization-runtime-jvm, etc
    Etc. However, I'm getting this Gradle error:
    Execution failed for task ':compileKotlinJvm'.
    > Could not resolve all files for configuration ':jvmCompileClasspath'.
       > Could not find org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:1.0.0-RC.
         Required by: ...
       > Could not find org.jetbrains.kotlinx:kotlinx-serialization-runtime:1.0.0-RC.
         Required by: ...
    Unless I read something incorrectly, I think that's what the GitHub README & the documentation on kotlinlang.org say to do... Did I do something wrong?
    v
    • 2
    • 4
  • j

    JCollardBovy

    08/26/2020, 7:34 PM
    Hi everyone! I'm a long standing user of kotlinx.serialisation but since upgrading to 1.0.0-RC I've been facing the following issue in my MPP:
    Overload resolution ambiguity: 
    public fun String.Companion.serializer(): KSerializer<String> defined in kotlinx.serialization.builtins
    public fun String.Companion.serializer(): KSerializer<String> defined in kotlinx.serialization.builtins
    
    Overload resolution ambiguity: 
    public fun <K, V> MapSerializer(keySerializer: KSerializer<TypeVariable(K)>, valueSerializer: KSerializer<TypeVariable(V)>): KSerializer<Map<TypeVariable(K), TypeVariable(V)>> defined in kotlinx.serialization.builtins
    public fun <K, V> MapSerializer(keySerializer: KSerializer<TypeVariable(K)>, valueSerializer: KSerializer<TypeVariable(V)>): KSerializer<Map<TypeVariable(K), TypeVariable(V)>> defined in kotlinx.serialization.builtins
    I've checked the dependencies downloaded by Gradle and indeed see that there are 2 identical artefacts for JVM, but that's not the case for common, JS or native. I only have a single dependency declared on the common module for
    org.jetbrains.kotlinx:kotlinx-serialization-core:1.0.0-RC
    Has anyone experienced something similar and could shed some light on how to solve it?
    m
    • 2
    • 1
  • p

    pajatopmr

    08/27/2020, 7:19 AM
    I found this 1+ year old comment while trying to debug some Kotlin JVM serialization code I am working on: "Kotlin serialization is more like a serialization code generator than a serialization library. Most JSON libraries are more for reading/writing Json rather than generating it." Given the hassles I've had trying to configure Gradle to be happy with the documented use of Kotlin serialization, I'm thinking this comment is meant for my application and I should be looking to GSON or Jackson rather than a Kotlin solution. My app definitely wants a library type solution: given a class get the JSON representation as a string and vice versa. But while the former does not involve code generation, the latter might, so I'm confused. And my preferences are for a pure Kotlin solution if at all possible. Advice, as in "how would you approach this problem - keep troubleshooting or switch to Jackson or GSON"?
    a
    m
    +2
    • 5
    • 11
  • p

    pajatopmr

    08/27/2020, 7:43 AM
    If memory serves, when using Kotlin serialization with KMP, I had to tell Gradle that I was using "experimental" features. Is this still necessary with Kotlin 1.4.0 code that is JVM (not KMP)? When I enable the serialization plugin, all dependencies are colored red in IntelliJ with no clear error message. A pointer to a working sample Kotlin/JVM app using 1.4.0 serialization in a Kotlin DSL gradle file would be very helpful.
    n
    • 2
    • 4
  • h

    hiperbou

    08/27/2020, 12:34 PM
    Hello, I updated kotlinx.serialization to 1.0.0-RC and this code that used to work on 0.9.1, now throws an error. It seems caused by the "id" property being used in the default initializer of the "otherData" property.
    @Serializable
    data class OtherData(val id:String)
    
    @Serializable
    data class MyData(val id: String = "", val otherData: OtherData = OtherData(id))
    • 1
    • 1
  • r

    rrva

    08/28/2020, 9:24 AM
    it would be nice to have a mode where you can run kotlin 1.4 plugin but work with old codebases
    j
    • 2
    • 3
  • u

    ursus

    08/28/2020, 8:22 PM
    Is streaming comming?
    v
    • 2
    • 1
  • c

    Chris Fillmore

    09/01/2020, 12:18 AM
    Hi everyone, maybe this is a dumb question but suppose I do this:
    @Serializable
    data class MyClass(val myProp: String, private val myPrivateProp: String)
    does
    myPrivateProp
    get serialized?
    m
    n
    n
    • 4
    • 13
  • n

    Nicolas Bourdin

    09/01/2020, 2:39 PM
    Hello, I've updated my kotlin version to 1.4 and kotlinx serialization to 1.0.0-RC And i get the following error when i try to build for ios Compilation failed: IrPropertyPublicSymbolImpl for public kotlinx.serialization.internal/EMPTY_SERIALIZER_ARRAY|-1756714926106261760[0] is already bound: PROPERTY name:EMPTY_SERIALIZER_ARRAY visibility:internal modality:FINAL [val] Any idea ? Thanks
    e
    • 2
    • 1
  • e

    Evan

    09/01/2020, 6:56 PM
    I just updated to Kotlin 1.4 and serialization 1.0.0-RC in my KMM project and I’m getting the error:
    Compilation failed: Deserializer for declaration public kotlinx.coroutines/SingleThreadDispatcher|null[0] is not found
    Does this look familiar to anyone? EDIT: I reverted back to 0.20.0 and have the same issue
    • 1
    • 1
  • t

    tim

    09/01/2020, 8:02 PM
    Hi all, i'm starting a new project and considering kotlinx.serialization over jackson which I am using currently. The project is microservices-based so restful and graphql endpoints which have a decent throughput level (1 request per second average). I understand that kotlinx.serialization is nearly 1.0.0 and was curious on anyone else experiences good or bad/would you recommend a move to kotlinx.serial from jackson? Thanks for your thoughts in advance 🙏
    e
    c
    +4
    • 7
    • 26
  • t

    Tmpod

    09/01/2020, 8:57 PM
    Hey! I'm trying to write a custom decoder for a little argument parsing thing I'm working on and it's going all good, except that I can't seem to figure out a way to make enums case insensitive. The thing is that
    decodeEnum
    is given a string that it should try to match to a enum value index, but
    SerialDescriptor#getElementIndex
    doesn't seem to have any way to do a case insensitive lookup. Any ideas how I might achieve this?
    • 1
    • 1
  • o

    Ovsyannikov Alexey

    09/03/2020, 12:15 PM
    Hello, I have faced with problem on JS Browser target. It is very strange, but all serial formats can't decode data which were incoded by themself. The most strangest here that I have created tests which should represent this issue, but they was correctly passed. I have tried to encode bytearra with cbor. Serializer was
    ListSerializer
    with data class subserializer, which have one custom serializer in it. As a result on trying to decode encoded bytearray I got error like
    Expected array, but found 00
    . I have tried to find some known issue on github or in the google, but didn't find it. Maybe, somebody here faced this too and could help me?
    n
    a
    t
    • 4
    • 17
  • l

    louiscad

    09/04/2020, 10:40 AM
    I know inline classes are not supported out of the box, but are they if we have a custom serializer for them?
    ➕ 9
    j
    a
    • 3
    • 2
  • j

    Jess Brent

    09/07/2020, 12:59 AM
    hello! i'm new to this library, can anyone point me to the right doc or an example to help me figure out how to handle de/serialization in cases where the data comes in a very specific format like this:
    {
      "op": "op type",
      "data": {
        "id": "",
        "name": ""
      }
    }
    for some context, the server utilizes both http and websockets. the op is something like
    GetSite
    or
    GetUser
    and the data block is an array of the op's values. right now i'm running into an issue where it can't figure out what to use for the data block when receiving a response on the websocket. i'm starting to feel like it won't be possible to utilize one set of classes for both http/ws. i got the following to work but something about it just feels hacky 😓
    @Serializable
    class SampleRequest {
        private val op = "GetThing"
        var data: Data
    
        constructor(auth: String?): super() {
            data = Data(auth)
        }
    
        @Serializable
        class Data(
            val auth: String?
        )
    }
    @Serializable
    class SampleResponse {
        private val op = "GetThing"
        var data: Data
        
        constructor(id: Int, name: String): super() {
            data = Data(id, name)
        }
        
        @Serializable
        class Data(
            val id: Int,
            val name: String
        )
    }
    t
    • 2
    • 6
  • f

    fkrauthan

    09/08/2020, 1:05 AM
    the return type works fine (e.g.
    MyResponse<SpecificResponse>
    as return type) but I get a no serializer found for
    MyRequest
    even though I can use serialization manual of an instance correctly.
    j
    • 2
    • 14
  • n

    natario1

    09/10/2020, 11:10 AM
    Hi 👋 I have many model classes extending a base interface like:
    class BaseModel {
        val keys: Set<String> 
        fun <T> get(key: String): T?
        fun <T> set(key: String, value: T?)
    }
    Basically, it works as a
    Map<String, Any?>
    and we can assume that the actual values are something that can be serialized, like numbers or strings. Then I have concrete models e.g.
    class UserModel : BaseModel
    ,
    class PostModel : BaseModel
    and so on. How can I make these classes serializable? I tried to write a common KSerializer and can handle serialization like:
    @Serializer(UserModel::class)
    object UserSerializer : BaseSerializer<UserModel>({ UserModel() })
    
    @Serializer(PostModel::class)
    object PostSerializer : BaseSerializer<PostModel>({ PostModel() })
    
    class BaseSerializer<M : BaseModel>: KSerializer<M> {
    
        override fun serialize(encoder: Encoder, model: T) {
            for (key in model.keys) {
                encoder.encodeString(key)
                val value = model.get(key)
                when (value) {
                    is Int -> encoder.encodeInt(value)
                    is Long -> encoder.encodeLong(value)
                    is String -> encoder.encodeString(value)
                    else -> error()
                }
            }
        }
    }
    But then I have no idea of how to implement
    deserialize
    (looks like order matters there...?) and
    descriptor: SerialDescriptor
    (not even sure what this is). I might get it working but I don't think I'm doing things in the correct way. Can anyone help? The BaseModel also has a working Parcelable implementation, if that matters.
    e
    • 2
    • 8
  • b

    bitkid

    09/10/2020, 11:10 AM
    is the Json class (created with
    Json { allowStructuredMapKeys = true }
    ) thread safe? especially this call
    json.encodeToString(someData)
    v
    • 2
    • 1
Powered by Linen
Title
b

bitkid

09/10/2020, 11:10 AM
is the Json class (created with
Json { allowStructuredMapKeys = true }
) thread safe? especially this call
json.encodeToString(someData)
v

Vsevolod Tolstopyatov [JB]

09/16/2020, 6:50 PM
Yes, Json instances are generally thread-safe
View count: 6