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

    Adam S

    04/03/2022, 9:55 PM
    Hi, I've made a 'KSerializer to TypeScript generator'. It will take an
    @Serializer
    annotated class and generate some TypeScript interfaces - so they can generate compatible JSON. The basics are in, and it needs more work to finish up some of the tricky bits. Please take a look! https://github.com/adamko-dev/kotlinx-serialization-typescript-generator/ It's available from JitPack. There's code examples in the docs directory
    👍 3
    a
    • 2
    • 4
  • l

    Luoqiaoyou

    04/04/2022, 12:31 PM
    Can I use kotlinx.serialization to decode/encode Swift Model(with Encodable/Decodable Protocal) to/from json string?
    g
    • 2
    • 1
  • r

    ribesg

    04/05/2022, 10:06 AM
    What do you do when kotlinx.serialization tries to decode everything as the wrong model?
    • 1
    • 1
  • s

    ste

    04/05/2022, 6:21 PM
    Hi all! Given the following JSONs:
    { "nav": { "watch:" {...} } }
    { "nav": { "browse:" {...} } }
    How can I deserialize
    Nav
    based on its key (
    "watch" | "browse"
    )? This is what I tried:
    @Serializable
    data class Nav(
      val action: Action
    )
    
    @Serializable
    sealed class Action {
      @Serializable
      @SerialName("watch")
      data class Watch(...) : Action()
    
      @Serializable
      @SerialName("browse")
      data class Browse(...) : Action()
    }
    But it doesn't work -
    Field 'action' is required for type with serial name Nav
    ; what am I missing?
    a
    d
    • 3
    • 9
  • m

    martypitt

    04/07/2022, 12:08 AM
    I've just updated to Kotlin 1.6.10 (was 1.4.32) and Serialization 1.3.2 (was 1.1.0) I'm getting a runtime error in my tests when trying to serialize a sealed class:
    java.lang.NoSuchMethodError: 'void kotlinx.serialization.internal.ObjectSerializer.<init>(java.lang.String, java.lang.Object, java.lang.annotation.Annotation[])'
    Inside`kotlinx.serialization.internal.ObjectSerializer`, I see the constructor. (It's scoped
    internal
    , not sure how scoping rules apply here, given the code is generated)
    @PublishedApi
    @OptIn(ExperimentalSerializationApi::class)
    internal class ObjectSerializer<T : Any>(serialName: String, private val objectInstance: T) : KSerializer<T> {
    
        @PublishedApi // See comment in SealedClassSerializer
        internal constructor(
            serialName: String,
            objectInstance: T,
            classAnnotations: Array<Annotation>
        ) : this(serialName, objectInstance) {
            _annotations = classAnnotations.asList()
        }
    • 1
    • 2
  • c

    christophsturm

    04/07/2022, 9:16 AM
    is it possible to make idea issue a warning if a data class with enums that have no
    @SerialId
    is serialized to protobuf? (protobuf serializes enums as ints and when they have no serialId the order matters. In json thats not a problem because enums are serialized as string.
    p
    • 2
    • 1
  • l

    Landry Norris

    04/07/2022, 6:46 PM
    I’m following along with https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/polymorphism.md#objects and I found that the list of multiple objects caused the type to show up, but if I only had EmptyResponse, then the output would just be [{}]. Is there a way to force it to give the type when there’s only one object?
    d
    e
    • 3
    • 17
  • j

    Jorge Bo

    04/08/2022, 5:45 PM
    Hi, basically i have two Map<String,Market> and Map<String,Station>, they are used for deserializing get calls.
    json {
    serializersModule = SerializersModule {
        contextual(Map::class) { MarketMapSerializer }
        contextual(Map::class) { StationMapSerializer }}
    }
    
     object MarketMapSerializer :
            JsonTransformingSerializer<Map<String, Market>>(MapSerializer(String.serializer(), Market.serializer())) {
            override fun transformDeserialize(element: JsonElement): JsonElement {
                return JsonObject(element.jsonObject.filterNot { (k, _) ->
                    k == "token"
                })
            }
        }
    
        object StationMapSerializer :
            JsonTransformingSerializer<Map<String, Station>>(MapSerializer(String.serializer(), Station.serializer())) {
            override fun transformDeserialize(element: JsonElement): JsonElement {
                return JsonObject(element.jsonObject.filterNot { (k, _) ->
                    k == "token"
                })
            }
        }
    and i'm getting this exception. Exception in thread "main" kotlinx.serialization.modules.SerializerAlreadyRegisteredException: Contextual serializer or serializer provider for class kotlin.collections.Map already registered in this module. Is it possible to specify types in contextual mapping?
    e
    • 2
    • 1
  • a

    Ayfri

    04/18/2022, 8:27 PM
    Hi, how can I write a serialiazer for a class where it has two properties
    client
    &
    environment
    , and if only
    client
    is set, it's saved as a String, else as an object containing both ?
    a
    e
    • 3
    • 5
  • a

    Ayfri

    04/18/2022, 10:08 PM
    Hi, I'm trying to use a JsonTransformingSerializer to transform an array of strings into one string if there is only one and keep as array else I'm using this
    override fun transformSerialize(element: JsonElement): JsonElement {
        require(element is JsonArray) // this serializer is used only with lists
        return element.singleOrNull() ?: element
    }
    Which is the exact code from the documentation but I'm getting nothing when there's one string and an array if multiple, what I'm doing wrong 🤔
    • 1
    • 1
  • j

    Joel Steres

    04/18/2022, 11:56 PM
    Hi. I am trying to merge a serialized data class into a json object which may have values not included in the data class. I am doing something similar to this.
    @Serializable
    data class Xxx(...) {
        fun merge(apiSnapshot: String): JSONObject {
            val merged = JSONObject(apiSnapshot)
            Json.encodeToJsonElement(this).jsonObject.entries.forEach { (key, value) ->
                if (value == null) {
                    merged.remove(key)
                } else {
                    merged.put(key, value)
                }
            }
            return merged
        }
    }
    However, the values are from the serialized
    JsonObject
    are all strings, including nulls. Is there a way to do this that preserves the type? I also tried
    encodeToString
    and parsing with
    JSONObject
    , which does preserve the types, but I lost nulls when I did this. I could combine the two approaches but I’m hoping there is a more elegant approach.
    e
    • 2
    • 4
  • c

    christophsturm

    04/19/2022, 10:02 AM
    is better error messages for json parsing errors on the roadmap? it would be cool have a list of problems.
    listOf(MissingField("surname"), WrongType("age", was=INT, expected=STRING))
    , and also a path to field names when something is missing in a nested object.
    e
    • 2
    • 10
  • a

    Ayfri

    04/19/2022, 7:50 PM
    Hi, how can I create a serialiazer for an Enum where it would serialize as an int (from the
    value
    field, using an interface to ensure that field exists), and deserialize as the enum value For now I have the serializer working and it was pretty easy, but what should be the deserializer ?
    e
    • 2
    • 9
  • h

    hugo.matilla

    04/20/2022, 2:13 PM
    Hello, I have a JSON where the keys are the ids.
    {
      "0": {"name": "John"},
      "1": {"name": "Jane"},
      "2": {"name": "Pete"},
      ...
    }
    I'm super new to the Serialization library, and I can't find which will be the best approach to deserialize it and have the id as part of the object? Something like this:
    Person (id: Int, name: String)
    Thank you🙂
    p
    • 2
    • 7
  • g

    George

    04/21/2022, 6:46 AM
    Hello, in case the serializer throws for various reasons, which is the optimal way to handle the throwing and return a bad response? im using this but i do not like it much because i try-catch. im looking for a way to avoid that.
    n
    • 2
    • 2
  • v

    Vivek Modi

    04/22/2022, 11:14 AM
    Hey Guys, I am using sealed class to handle api response. I am trying some code but getting some error. Can somone suggest me? Please see in the thread.
    • 1
    • 4
  • v

    Viktor Orlyk

    04/24/2022, 3:56 PM
    Hi guys, can you please help me understand where I am wrong? Hi, all. Maybe someone can help me understand what is the problem with my code for class serialization? Not to polute the channel posted question on stackoverflow. Thanks in advance! https://stackoverflow.com/questions/71988144/serializer-for-class-is-not-found-mark-the-class-as-serializable-or-prov thanks
    p
    • 2
    • 1
  • k

    kierans777

    04/25/2022, 3:54 AM
    I'm using
    kotlinx-serialization
    in my MPP library, and all the tests run successfully on the JVM target. However when running
    iosX64Test
    I'm getting a segmentation fault. I've stripped the code right back and I'm not sure what's causing it. Can someone help me understand how to debug this please?
    • 1
    • 1
  • g

    Grouvie

    04/27/2022, 9:39 AM
    I receive requests like:
    [2,"6bd18013-b33f-43bb-bf91-7745e5517dd2","StatusNotification",{"connectorId":1,"errorCode":"NoError","status":"Available"}]
    and
    [2,"5a3a42a2-212d-4815-9581-f64ce55fd6cc","Heartbeat",{}]
    over websockets to which I then answer:
    [3,"6bd18013-b33f-43bb-bf91-7745e5517dd2",{}]
    and
    [3,"5a3a42a2-212d-4815-9581-f64ce55fd6cc",{"currentTime":"2022-04-27T11:29:38.179938700"}]
    . What is the most elegant way to deserialize, serialize and answer them?
    e
    • 2
    • 8
  • b

    bbaldino

    04/27/2022, 4:49 PM
    I’m trying to do something where: any time one of a subset of fields are changed in a class, I want to write a serialized version of that class to some store. I was looking at something like this:
    @Serializable
    class Foo {
       var id: String by Delegates.observable("initialId", ::onChange)
    
       private fun onChange() {
          keyStore.set("foo", Json.encodeToString(this))
       }
    }
    but this won’t work because delegates don’t get serialized. Is there a good way to accomplish something like this?
    o
    • 2
    • 2
  • j

    Joel Steres

    04/29/2022, 12:46 AM
    My question started out about how to rewrite a JsonTransformingSerializer as a KSerializer. I think that is now resolved. My remaining question is whether a new serializer can be made to be the default for a type so it doesn’t need to be annotated every time.
    e
    • 2
    • 9
  • s

    Sebastian Schuberth

    05/02/2022, 4:36 PM
    I'm trying to write a custom serializer for
    Enum
    , the "common base class of all enum classes", but I'm struggling with the syntax for the generic type parameter. Has some done this successfully?
    • 1
    • 2
  • l

    Landry Norris

    05/02/2022, 9:19 PM
    I’m using polymorphic serialization in an app, and I get a serialization error when I run in release mode, but not debug mode.
    e
    • 2
    • 12
  • b

    bbaldino

    05/02/2022, 11:55 PM
    I saw it’s possible to customize the value of the
    type
    field when serializing polymorphic classes…I’m curious if it’s possible to customize the name of that field (
    type
    ) via an annotation? Or would that require a custom serializer?
    e
    • 2
    • 6
  • h

    hfhbd

    05/04/2022, 7:40 AM
    Hey, I wan to use a custom annotation class during encoding. So I marked my annotation class with @SerialInfo and I use
    descriptor.getElementAnnotations(index)
    , but the annotation for this property is not found. Did I miss something?
    • 1
    • 2
  • h

    hfhbd

    05/06/2022, 10:04 AM
    Anybody interested in ordered CSV and Fixed Length Formats? https://github.com/hfhbd/kotlinx-serialization-csv
    🆒 1
    🎉 2
    :nice: 1
    f
    • 2
    • 2
  • a

    asarazan

    05/07/2022, 11:32 PM
    Cross-posting from #opensource: https://kotlinlang.slack.com/archives/C2YH04E3S/p1651966101700999
    👍 2
    🆒 1
    a
    • 2
    • 1
  • d

    dave08

    05/08/2022, 10:57 AM
    Are json lists deserialized in order? If so, does the yaml plugin make kotlinx serialization lose that order? And is there any way to make sure the order is kept? Our source files are in yaml and need to be deserialized to kotlin data classes in a very specific order...
    d
    a
    • 3
    • 10
  • d

    dany giguere

    05/08/2022, 3:30 PM
    I’m trying to set up Ktor with exposed and I can’t figure out how to serialize my model. I have
    object Cars: IntIdTable() {
        val name = varchar("name", 128)
        val year = integer("year")
    }
    
    class Car(id: EntityID<Int>): IntEntity(id) {
        companion object : IntEntityClass<Car>(Cars)
        var name by Cars.name
        var year by Cars.year
    }
    
    //@Serializable
    class SerializedCar(id: EntityID<Int>, name: String, year: Int): IntEntity(id)
    then :
    class CarDAO {
        private fun resultRowToCar(row: ResultRow) = SerializedCar(
            id = row[Cars.id],
            name = row[Cars.name],
            year = row[Cars.year]
        )
    
        suspend fun show(id: Int): SerializedCar? = transaction {
            Cars
                .select { Cars.id eq id }
                .map(::resultRowToCar)
                .singleOrNull()
        }
    }
    and my route is :
    get("/cars/{id}") {
                val id = call.parameters.getOrFail<Int>("id").toInt()
                call.respond(mapOf("car" to carDAO.show(id)))
            }
    but I get this error :
    500: kotlinx.serialization.SerializationException: Serializer for class 'SerializedCar' is not found.
    Mark the class as @Serializable or provide the serializer explicitly.
    You can see the project here for more info:
    <https://github.com/danygiguere/ktor-kotlin-example>
    And if I uncomment
    //@Serializable
    , my IDE tells me :
    Impossible to make this class serializable because its parent is not serializable and does not have exactly one constructor without parameters
    h
    • 2
    • 1
  • m

    Mendess

    05/11/2022, 3:59 PM
    Is it possible to implement my own custom format and hook into the
    @Serializable
    infrastructure? Aka, is it possible for me to define something like
    MyFormat.decodeFromString
    and
    MyFormat.encodeToMyFormat
    m
    a
    • 3
    • 6
Powered by Linen
Title
m

Mendess

05/11/2022, 3:59 PM
Is it possible to implement my own custom format and hook into the
@Serializable
infrastructure? Aka, is it possible for me to define something like
MyFormat.decodeFromString
and
MyFormat.encodeToMyFormat
m

Mitchell Syer

05/11/2022, 4:03 PM
Yep, there are quite a few that do already, here is a list of most of them. https://github.com/Kotlin/kotlinx.serialization/tree/master/formats
m

Mendess

05/11/2022, 4:03 PM
yeah I saw that, but I didn't find instructions on how to implement my own
m

Mitchell Syer

05/11/2022, 4:05 PM
I believe the docs for that are here https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/formats.md#custom-formats-experimental
m

Mendess

05/11/2022, 4:06 PM
I see, I missed it
thanks!
a

andylamax

05/12/2022, 6:30 AM
I also missed this. Much thanks for this germ
View count: 15