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

    benkuly

    05/12/2022, 4:14 PM
    Are there plans to support suspending `serialize`/`deserialize`? I need to make a database/cache call within deserialize to determine which
    DeserializationStrategy
    should be used depending on a field value.
    n
    d
    • 3
    • 9
  • y

    Yao-Wen Mei

    05/13/2022, 4:27 AM
    👋 Hello, team! I am wandering where can we find more reference for how a
    format de/encoder
    [Link] works with a
    serializer
    [Link]. I am following the Kotlin Serialization Guide, and I can see this
    encodeSerializableValue()
    method is how de/encoder interact with serializer, but wandering if I can find more detail instructions or example guide. Thank you.
    encoder.encodeSerializableValue(serializer, value)
    e
    • 2
    • 1
  • k

    kevin.cianfarini

    05/13/2022, 2:26 PM
    On Kotlin/Native (iOS) I’m getting an unsupported call of refied inlined function when using
    Json.encodeToString(value: T)
    . This is the following code snippet.
    override var market: Market?
            get() = marketJson?.let(json::decodeFromString)
            set(value) { marketJson = value?.let(json::encodeToString) }
    Is this a potential bug in K/N or serialization? Using Kotlin 1.6.10, serialization 1.3.1. Full stack trace in thread.
    a
    • 2
    • 3
  • p

    Philip Dukhov

    05/15/2022, 7:10 AM
    I'm trying to map enum to int values:
    @Serializable
    enum class ItemType {
        @SerialName("0") Zero,
        @SerialName("1") First,
    }
    But it fails with the following exception:
    JsonDecodingException: Unexpected JSON token at offset 194: Expected quotation mark '"', but had '1' instead
        JSON input: ....."type":1,.....
    It doesn't seem to work because
    SerialName
    is expecting a string and json has an int. I can think of two ways to solve this: 1. Enabling lenient mode - I don't like this solution as it also removes restrictions from other fields, which I prefer to keep 2. Implementing a custom serializer - seems like too much of boilerplate code for such a simple task Am I missing something?
    a
    • 2
    • 7
  • s

    Sebastian Schuberth

    05/16/2022, 3:39 PM
    Hi, is there a way to write generic serializers for JVM classes that do nothing but use
    toString()
    ? Currently, I'm writing code like
    @Serializer(File::class)
    object FileSerializer : KSerializer<File> {
        override fun serialize(encoder: Encoder, value: File) = encoder.encodeString(value.toString())
        override fun deserialize(decoder: Decoder) = File(decoder.decodeString())
    }
    
    @Serializer(URI::class)
    object URISerializer : KSerializer<URI> {
        override fun serialize(encoder: Encoder, value: URI) = encoder.encodeString(value.toString())
        override fun deserialize(decoder: Decoder) = URI(decoder.decodeString())
    }
    but this duplication seems rather dumb. Can I somehow generalize these serializers into one, and use that single serializer for both
    File
    and
    URI
    ?
    p
    e
    p
    • 4
    • 12
  • y

    Yao-Wen Mei

    05/17/2022, 11:08 AM
    hi, I want to serialize a custom class into a nested map (with my own encoder, not introducing JSON into my code base). For example, if I have my data classes defined like this:
    @Serializable
    data class Project(val name:String, val owners: List<Users>)
    
    @Serializable
    data class Users(val name: String)
    After serialization, I wish to get a nested map equals to:
    val map = mutableMapOf<String, Any>()
    map.put("name", "project_name")
    map.put("owners", listOf(mapOf("name" to "user1"), mapOf("name" to "user2"))
    Could you please give me some hint how can I implement this
    Encoder
    please ( I do have a
    Decoder
    working BTW)? Should my Encoder extend the
    AbstractEncoder()
    or
    TaggedEncoder()
    ? May I get some document for how to implement this? The official guide only contains an example for serializing to
    List
    , but does not show how to get the key values if I want to serialize to
    Map
    . Thank you very much.
    d
    • 2
    • 1
  • a

    Alejandro Moya

    05/17/2022, 6:07 PM
    Hi, quick question, I have and endpoint that has a dynamic property, it could be a
    String
    , an
    Integer
    or a
    Boolean
    , is there a way to achieve that behaviour with serialization?
    p
    n
    • 3
    • 7
  • r

    ribesg

    05/18/2022, 10:01 AM
    Beware of the default behavior on default values! It can lead to very unexpected results…
    @Serializable
        data class Event(
            val id: String,
            val date: Date = Date.now(),
        )
    
        @Test
        fun test() {
            repeat(100) {
                println(Json.encodeToString(Event("Test")))
            }
        }
    …
    {"id":"Test"}
    {"id":"Test"}
    {"id":"Test","date":"2022-05-18T10:00:47.011Z"}
    {"id":"Test"}
    {"id":"Test"}
    {"id":"Test"}
    …
    😯 2
    😱 3
    n
    • 2
    • 6
  • o

    Ovsyannikov Alexey

    05/18/2022, 10:05 AM
    Hello everybody 🙂 I wished ask somebody to help me investigate a bug in compile time related to serialization. This bug break my builds already half a year, fortunately the project in the report is a pet-project and I am able to wait a fix, but it is a little bit long-play issue and I wished to ask help here 🙂 thank you
    • 1
    • 1
  • z

    zt

    05/19/2022, 7:50 PM
    How would I write a custom serializer for json input that looks like this
    [ { "somekey": { } }, { "someotherkey": { } } ]
    I wanna be able to check the name of the first key in the object and then serialize to a specific class depending on what it is
    l
    e
    r
    • 4
    • 11
  • s

    Slackbot

    05/20/2022, 10:31 PM
    This message was deleted.
    d
    l
    • 3
    • 2
  • m

    Matthew Olsson

    05/21/2022, 2:12 AM
    Is it possible to deserialize an array into an object? For example, turning something like
    ["Bob", 24]
    into
    class Person(val name: String, val age: Int)
    . Assuming of course that I already know the array corresponds to the
    Person
    class (in reality, my data looks more like
    { "person": ["Bob", 24] }
    j
    e
    • 3
    • 18
  • j

    Jan

    05/22/2022, 10:26 AM
    Why doesn't that work you literally can see that I have kotlinx serialization, ktor client and content negotiations:
    b
    h
    • 3
    • 17
  • p

    Pedro Henrique

    05/22/2022, 7:47 PM
    I'm trying to deserialize a CBOR message that I'm getting over FFI (Project Panama), but I keep getting a
    kotlinx.serialization.cbor.internal.CborDecodingException: Expected start of string, but found 50
    error. The byte array data seems to be the same as the original one in Rust when converting them to a hexadecimal format. I can deserialize normally the same data on Rust through the
    cbor4ii
    library. I also tried using another library (
    cborium
    ) and I still get the same error in the Kotlin side.
    d
    • 2
    • 8
  • v

    Václav Škorpil

    05/23/2022, 9:48 AM
    Hi i need to call SOAP api. There is no official library so i am using https://github.com/pdvrieze/xmlutil . Is there a way how to specify more namespaces than one, using this library? My soap request is like this. I need to create a data classes to represent it.
    <?xml version="1.0" encoding="utf-8"?>
    <soapenv:Envelope xmlns:soapenv="<http://schemas.xmlsoap.org/soap/envelope/>" xmlns="<http://www.pds.eu/vOKO/v0200>" xmlns:eph="<http://www.ccv.cz/EPH_GCP01G>">
       <soapenv:Body>
          <Request vOKOid="EPH_GCP01G">
             <RequestContent>
                <eph:REQUEST>
                   <eph:GETDATA>1</eph:GETDATA>
                   <eph:IDLAST>22</eph:IDLAST>
                </eph:REQUEST>
             </RequestContent>
          </Request>
       </soapenv:Body>
    </soapenv:Envelope>
    As you can see, there are more than one namespace in the envelope.I xmlutil is only @XmlSerialName which can specify only one namespace. How should i handle this?
    d
    p
    • 3
    • 4
  • j

    jean

    05/23/2022, 1:06 PM
    I have defined the following classes :
    interface DeviceAttribute<T> {
        val name: String
        val value: T
    }
    
    @SharedImmutable
    internal val module = SerializersModule {
        polymorphic(baseClass = DeviceAttribute::class, baseSerializer = null) {
            subclass(AlarmEntryDevice::class)
            default { Unknown.serializer() }
        }
    }
    
    @Serializable
    data class Device(
        val id: String,
        val name: String,
        val icon: String,
        val iconOptions: List<String>,
        val attributes: List<DeviceAttribute<*>> = emptyList(),
        val profiles: List<ActiveProfileMode>?,
    )
    But I get this error
    Serializer has not been found for type 'Any?'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
    Adding the annotation doesn’t change anything though. What should I do?
    d
    e
    • 3
    • 9
  • j

    jean

    05/23/2022, 8:54 PM
    Is it possible to tell a
    SerializersModule
    to look for an attribute called
    name
    instead of
    type
    without registering a custom serializer?
    e
    • 2
    • 6
  • i

    Igor Kolomiets

    05/25/2022, 2:53 PM
    My system persists the following object graph as JSON serialized with kotlinx.serialization:
    @Serializable
    data class Category(val id: String, val children: Set<Category> = emptySet())
    For the sake of having “stable” diff of the updated JSON file, I’d like to enforce order of the
    children
    Set’s elements based on lexicographic order of the element’s
    id
    field. The solution I was able to come up with is to use custom serializer based on `JsonTransformingSerializer`:
    object CategorySetSerializer : JsonTransformingSerializer<Set<Category>>(SetSerializer(Category.serializer())) {
        override fun transformSerialize(element: JsonElement) = super.transformSerialize(
            if (element is JsonArray)
                JsonArray(element.sortedBy { it.jsonObject["id"]?.jsonPrimitive?.content })
            else
                element
        )
    }
    
    @Serializable
    data class Category(
        val id: String,
    
        @Serializable(with = CategorySetSerializer::class)
        val children: Set<Category> = emptySet()
    )
    Unfortunately, this solution seems too low level, brittle and JSON specific. What can be other approaches to enforce particular ordering of serialized Set’s elements? Ideally, I’d like to pass in the
    @Serializable
    my custom comparator when specific Set’s elements ordering is required.
    e
    • 2
    • 2
  • n

    nikolaymetchev

    05/26/2022, 11:45 AM
    Hi, Is there an easy way to mutate a
    JsonObject
    ? If I have such an object already and I wish to add a couple of elements somewhere nested deep inside is that possible programatically? I think I would have to effectively clone the whole thing myself in order to achieve that.
    i
    • 2
    • 1
  • y

    Yao-Wen Mei

    05/26/2022, 6:00 PM
    will Kotlin serialization plugin be able to capture annotations applied on setters or getters?
    @SerialInfo
    @Target{
    AnnotationTarget.PROPERTY_SETTER,
    AnnotationTarget.PROPERTY_GETTER}
    annotation class KDocumentId
    
    data class File( @get: KDocumentId val name:String?= null)
    // this will just return empty list []
    descriptor.getElementAnnotations(elementIndex)
    h
    • 2
    • 2
  • t

    Tomas Kormanak

    05/27/2022, 1:46 PM
    Hi, is it possible to override serializer? I have a library class annotated as
    @Serializable
    but I would like to use different serializer than default one but I can't change the library code.
    e
    e
    • 3
    • 10
  • z

    zt

    05/28/2022, 1:15 PM
    I made this serializer for my json structure
    companion object Serializer : JsonContentPolymorphicSerializer<Renderer>(Renderer::class) {
        override fun selectDeserializer(element: JsonElement) = when {
            "slimVideoMetadataSectionRenderer" in element.jsonObject -> SlimVideoMetadataSectionRenderer.serializer()
            "itemSectionRenderer" in element.jsonObject -> RelatedItemsRenderer.serializer()
            "shelfRenderer" in element.jsonObject -> ShelfRenderer.serializer()
            else -> throw NoWhenBranchMatchedException()
        }
    }
    though how would I make it serialize using the object inside of the key?
    e
    • 2
    • 3
  • j

    jean

    05/31/2022, 2:02 PM
    I’m getting this error message
    Polymorphic serializer was not found for class discriminator 'batteryPercentage', JSON input: {"name":"batteryPercentage","value":70}
    @JsonClassDiscriminator("name")
    interface DeviceAttribute
    
    @Serializable
    data class Device(
        val id: String,
        val name: String,
        val icon: String,
        val iconOptions: List<String>,
        val attributes: List<DeviceAttribute> = emptyList(),
        val profiles: List<ActiveProfileMode>?,
    )
    
    @Serializable
    @SerialName("batteryPercentage")
    data class BatteryPercentage(val value: Int) : DeviceAttribute
    What am I missing here?
    e
    r
    e
    • 4
    • 4
  • j

    Jan

    06/01/2022, 6:21 PM
    Why does that throw an exception? (thread)
    d
    • 2
    • 9
  • k

    kotlinforandroid

    06/02/2022, 8:02 PM
    How do I use sealed interfaces for union types properly? (thread)
    ✅ 2
    e
    • 2
    • 12
  • d

    DJ

    06/04/2022, 1:05 AM
    I have a json file I am parsing with ktx.serialization which has a
    $schema
    key at the top level. I am parsing it into a
    Map<String, Def>
    (Def is a class I have defined), so when the string value in the
    $schema
    key is encountered, it throws an exception. I simply want to ignore the value of the
    $scheam
    key, what is the best way to do this?
    k
    • 2
    • 2
  • k

    kotlinforandroid

    06/04/2022, 6:32 AM
    I need some help with deserialization. I get an
    IndexOutOfBoundsException
    and I do not really get why. (thread)
    • 1
    • 1
  • a

    Adam S

    06/04/2022, 11:30 AM
    I can define a serializer for a class in many places. On the class with
    @Serializable
    , on the field, for a whole file, in multiple ways with a SerializersModules, and there's also reflection. Is the order of priority defined somewhere? I'm asking because I want to see how to override a serializer that's defined on a class with
    @Serializable(with = ...)
    , and it's not clear in which order serializers are considered and selected.
    e
    • 2
    • 3
  • k

    Katyrin Roman

    06/08/2022, 6:20 AM
    After updating from com.android.tools.build:7.0.4 to com.android.tools.build:7.2.1, the application began to crash when calling the <reified T> StringFormat.encodeToString(value: T): String method. The bug manifests itself only in the release version, where there is: minifyEnabled true, shrinkResources true Has anyone come across a similar situation and have a solution?
    e
    • 2
    • 1
  • a

    ankushg

    06/10/2022, 6:12 PM
    Hey all! At some point, we started running into this issue: https://github.com/Kotlin/kotlinx.serialization/issues/1940 It’s not impacting our
    main
    branch, but we have a branch where we’ve made a couple structural changes (with absolutely no new
    @Serializable
    classes) and things are just breaking for mysterious reasons 😞 Has anyone else here experienced it? Any ways to narrow down the cause?
    s
    • 2
    • 3
Powered by Linen
Title
a

ankushg

06/10/2022, 6:12 PM
Hey all! At some point, we started running into this issue: https://github.com/Kotlin/kotlinx.serialization/issues/1940 It’s not impacting our
main
branch, but we have a branch where we’ve made a couple structural changes (with absolutely no new
@Serializable
classes) and things are just breaking for mysterious reasons 😞 Has anyone else here experienced it? Any ways to narrow down the cause?
s

Simon Bruins

06/12/2022, 4:09 PM
Had the same problem after updating to 1.7.0. Updating the KotlinX plugin seemed to do the trick.
a

ankushg

06/12/2022, 8:02 PM
Updating the KotlinX plugin seemed to do the trick.
which plugin? the kotlinx.serialization plugin?
s

Simon Bruins

06/14/2022, 12:50 AM
Yeah that one I think 🙂
View count: 23