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

    bjonnh

    01/20/2021, 6:49 PM
    How does one catch JsonDecodingException? seems like it is internal to kotlinx
    v
    • 2
    • 7
  • a

    Alexander

    01/20/2021, 7:47 PM
    Have a custom serializer:
    import kotlinx.serialization.*
    import kotlinx.serialization.json.Json
    
    // Uncomment to disable encoding default values
    // @Serializable
    internal class Action(
        val id: String,
        val routing: String? = null,
    )
    
    @Serializer(forClass = Action::class)
    object ActionSerializer : KSerializer<Action>
    
    fun main(args: Array<String>) {
        val action = Action(
            id = "1",
        )
        println(Json.encodeToString(ActionSerializer, action))
    }
    This code produces:
    {
      "id": "1",
      "routing": null
    }
    If you uncomment
    @Serializable
    annotation default values will be ignored. Is this behavior a bug or not?
    v
    s
    • 3
    • 2
  • f

    fkrauthan

    01/21/2021, 8:38 PM
    Hey for
    polymorphism
    it currently uses the
    type
    attribute. Is there any way to change the name? In my case I need it to look at the
    name
    attribute (which is the same as
    type
    just different name)
    d
    d
    • 3
    • 8
  • n

    Nikky

    01/23/2021, 11:49 PM
    has anyone made a https://json5.org/ version of serialization yet? that would be very nice to use for config file purposes
    b
    v
    • 3
    • 2
  • p

    pajatopmr

    01/24/2021, 1:27 PM
    After ~4 months or so doing a considerable amount of JSON rpc development that is heavily polymorphic (uses serialization extensively), my conclusion is that there are two essential paradigms for dealing with serializing polymorphic things: format + modules, or Json + serialization strategies. The latter has dominated my work so far but I have a hunch I might be selling format + modules short. If you use a lot of polymorphism and KXS, which approach do you use/prefer. If you've seen this question dealt with in a paper, written by Roman, no doubt, 🙂, do send me a link. Much appreciated.
    v
    • 2
    • 5
  • m

    Megan Teahan

    01/29/2021, 4:43 PM
    Hello all! I'm trying to serialize 
    Any
     in a nested Map and I'm using the @contextual method defined in this post:
    @Serializable
    data class Media(
        val id: String? = null,
        val title: String? = null,
        val tracking: Map<String, Map<String, @Contextual Any>> = mapOf(),
    )
    
    val json = Json {
        ignoreUnknownKeys = true
        serializersModule = SerializersModule {
        contextual(String.serializer()) // could be an Int
        contextual(Int.serializer()) // could be a String
        contextual(Boolean.serializer()) // could be a Boolean
       }
    }
    
    val media = json.decodeFromString(Media.serializer(), MediaResponse.json) //MediaResponse.json is a string
    I'm still getting this error
    kotlinx.serialization.SerializationException: Serializer for class 'Any' is not found.
    Mark the class as @Serializable or provide the serializer explicitly.
    Am I missing something?
    t
    • 2
    • 6
  • a

    Anarakul

    01/29/2021, 5:04 PM
    I am trying to use serialization with an
    enum class
    . I have read the appropriate documents (I think) and am using the appropriate annotations and strategies (I think), but I am still encountering a run-time issue immediately. I am also encountering a compile-time issue, I think, because the compiler doesn’t believe that there’s a
    serializer
    method on my
    enum class
    .
    r
    • 2
    • 22
  • r

    RedTahr1

    02/02/2021, 12:49 PM
    Hi, When changing serialization version from 1.0-M1-1.4.0-rc that was release with Kotlin 1.4.0 to 1.0.1 , Gradle says
    Failed to resolve: org.jetbrains.kotlinx:kotlinx-serialization-runtime:1.0.1
    Isn't this available on jcenter? or what should I do?
    k
    v
    • 3
    • 11
  • b

    Ben Woodworth

    02/02/2021, 10:24 PM
    I want to write an encoder for a format that only supports lists with elements of a single type. What's a good way to ensure that's the case when encoding collections and their elements? Right now I'm thinking of having a check in
    beginCollection
    to require
    descriptor.elementsCount == 1
    , but I'm not sure if that guarantees homogeneity in all cases. (I'm pretty sure it'll work for the standard collection serializers, but besides that I'm not sure)
    • 1
    • 1
  • k

    Karlo Lozovina

    02/02/2021, 11:17 PM
    oh, don't mind me, I think I've typed something wrong... this seems to work:
    "-Xopt-in=kotlinx.serialization.ExperimentalSerializationApi"
    in build.gradle.kts
    r
    • 2
    • 2
  • j

    Jérôme Gully

    02/05/2021, 10:58 AM
    Hi, had a hard time finding information about
    CommonEnumSerializer
    /
    EnumSerializer
    . I try to use openapi-generator KMP export to generate data classes from json swagger and generated models uses unresolved
    CommonEnumSerializer
    , for example
    @Serializable(with = Env.Serializer::class)
    enum class Env(val value: kotlin.String){
        notDeployed("not_deployed"),
        inDeployment("in_deployment"),
        deployed("deployed");
    
        object Serializer : CommonEnumSerializer<Env>("Env", values(), values().map { it.value.toString() }.toTypedArray())
    }
    What is the current way for doing that ? Or how to find/use
    CommonEnumSerializer
    🤓
    d
    • 2
    • 2
  • p

    pajatopmr

    02/05/2021, 3:13 PM
    Give a TypeScript interface: `interface Foo { foo?: integer | string }`how might I represent this in Kotlin with KXS?
    b
    • 2
    • 4
  • b

    bod

    02/06/2021, 2:49 PM
    Hello, World! I need to serialize a map of string to "anything" (could be an object, could be an int, a string, etc.). What's a way to declare the custom
    Serializer
    for this? (in particular, what
    SerialDescriptor
    can I use?) Thanks!
    n
    • 2
    • 4
  • t

    Tiago Nunes

    02/08/2021, 11:07 AM
    Hi everyone, the webservices I'm using return an object wrapped in another object:
    {
    "d": {
    "id": 3,
    "name": "Tiago"
    }
    }
    Is there any way to make it so that I don't have to make a wrapper class in every Serializable class? Something like @path, with XML Parser:
    @Path("Body/GetAllVehicleBrandsResponse")
    private List<InstallerVehicleBrand> allVehicleBrandsResult;
    (Here I didn't need to make a Body class)
    t
    • 2
    • 1
  • t

    Tiago Nunes

    02/08/2021, 8:11 PM
    Hi everyone, simple question: I have a JsonObject:
    val jsonObject = jsonElement.jsonObject
    How do I add a new entry to the object? (something like this:)
    jsonObject.addProperty(name, value)
    (name and value are both Strings)
    p
    • 2
    • 2
  • p

    pajatopmr

    02/09/2021, 2:48 PM
    Need some help here to serialize a property in a class that is a list of an interface. Specifically at line 47 I need to add something like
    @Serializable(with = ????) val list: List<Stuff>
    . But what ???? is is eluding me.
    d
    • 2
    • 7
  • i

    irus

    02/09/2021, 4:58 PM
    Json is
    StringFormat
    so it has methods like
    encodeToString/decodeFromString
    but is somehow available direct serialization/deserialization to ByteArray? Comparing to jackson that has
    writeValueAsBytes
    (create string with
    encodeToString
    and than convert to com.google.protobuf.ByteString, my case for PubSub):
    Benchmark          Mode  Cnt       Score       Error  Units
    JsonTest.jackson  thrpt   25  459596.078 ± 31782.902  ops/s
    JsonTest.kotlin   thrpt   25  301485.307 ± 19990.942  ops/s
    m
    p
    v
    • 4
    • 31
  • i

    irus

    02/10/2021, 11:11 AM
    https://kotlinlang.slack.com/archives/C7A1U5PTM/p1612889899095700
    Json.encodeToByteArray
    – why this not available? Any plans to implement direct encoding to
    ByteArray
    ?
    o
    v
    • 3
    • 4
  • r

    RedTahr1

    02/10/2021, 2:54 PM
    Any hint of how to register a serializer for ArrayList, since I get
    kotlinx.serialization.SerializationException: Class 'ArrayList' is not registered for polymorphic serialization in the scope of 'Any'.
    m
    • 2
    • 5
  • j

    jaqxues

    02/10/2021, 10:29 PM
    I suppose streaming support is still far away, so, if you do not want heavy memory usage, kotlinx.serialization is still not a valid option. Is the kotlinx.io repo even being worked on? simce I think the initial plans were to integrate it with that.
    a
    • 2
    • 2
  • a

    Andy Victors

    02/10/2021, 10:54 PM
    Can kotlin custom serializer be any help on decoding weird/invalid JSON? I could do this in Java with Gson using custom deserializer. The challenge is following (list of mixed objects - String, then Object) . I tried using official guide and wrote custom deserializer here too, however it produces error already in
    decoder.decodeStructure(descriptor)
    n
    • 2
    • 2
  • k

    Karlo Lozovina

    02/11/2021, 9:02 AM
    when deserializing to
    List<T>
    how does it pick what concrete type to use? ArrayList, LinkedList, etc...?
    p
    • 2
    • 1
  • t

    tylerwilson

    02/11/2021, 5:29 PM
    Hello. I am updating serialization to 1.1.0-RC, and using Kotlin 1.4.30-RC (latest available for Canary), but I get this error:
    Could not find org.jetbrains.kotlin:kotlin-stdlib-common:1.4.30-270.
    Required by:
        project :salonbiz-library > org.jetbrains.kotlinx:kotlinx-serialization-core:1.1.0-RC
        project :salonbiz-library > org.jetbrains.kotlinx:kotlinx-serialization-json:1.1.0-RC
    Do I perhaps have to add an explicit dependency to stdlib, or something else going on?
    m
    • 2
    • 6
  • t

    Tiago Nunes

    02/12/2021, 12:11 PM
    Hi everyone, I'm consuming data from a JSON API. Some responses contain decimal numbers. Depending in the culture-info field sent to the server, they might use dots (e.g. 18.312) or commas (e.g. 18,312) Is there some way I can interpret these both as Float in my Serializer class (Float only accepts dot notation)? Maybe through some custom field desserialization or something...?
    j
    • 2
    • 28
  • a

    Andy Victors

    02/12/2021, 4:49 PM
    Colleagues, any idea why serializer stumbles upon this valid JSON?
    coerceInputValues
    is true. (offset 22 is begin of first null)
    kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 22: Expected end of the array or comma
    JSON input: {"rows":[["Connected",null,null,null,null,null,null,.....
    • 1
    • 2
  • d

    Dariusz Kuc

    02/12/2021, 9:37 PM
    Hello 👋 Any suggestions on how to write a custom
    KSerializer
    that behaves similar to the built-in ones for primitives? e.g. I can deserialize
    Double
    from Number (Int/Float) or String representation
    var kotlinxDouble: Double = format.decodeFromString("""
        0
    """.trimIndent())
    println(kotlinxDouble)
    
    kotlinxDouble = format.decodeFromString("""
        1.0
    """.trimIndent())
    println(kotlinxDouble)
    
    kotlinxDouble = format.decodeFromString("""
        "2.0"
    """.trimIndent())
    println(kotlinxDouble)
    tried
    object BigDecimalStringSerializer : KSerializer<BigDecimal> {
    
        override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("BigDecimal", PrimitiveKind.STRING)
    
        override fun serialize(encoder: Encoder, value: BigDecimal) {
            encoder.encodeString(value.toString())
        }
    
        override fun deserialize(decoder: Decoder): BigDecimal {
            val raw = decoder.decodeString() // <-- blows up when not a String representation, i.e. on 0 and 1.0 values from above
            return BigDecimal(raw)
        }
    }
    Is there something like
    decoder.getRawValue
    or something like that?
    r
    d
    • 3
    • 9
  • d

    Dariusz Kuc

    02/15/2021, 6:44 PM
    Hello 👋 Is there a way to deserialize JSON response to just a hashmap? I have to handle the response where a field is an arbitrary JSON, e.g.
    @Serializable
    data class GraphQLResponse<T>(
        val data: T? = null,
        val errors: List<GraphQLError>? = null,
        val extensions: Map<Any, Any>? = null // complains about missing serializer for Any
    )
    a
    • 2
    • 6
  • m

    madsbf

    02/17/2021, 9:24 AM
    Hi everyone, Do you know if there is a way to add a default type for sealed class serialization or any discussion regarding this somewhere? Imagine that you have two Styles (default and dark):
    @Serializable
    sealed class Style {
    
       @SerialName("default")
       object Default : Style()
    
       @SerialName("dark")
       class Dark(...) : Style()
    }
    Now in order to future-proof the above in case new styles are introduced, we want to use the Default style in case a new type (“light” f.x.) is introduced. Is there some idiomatic way to do this - besides using a custom serializer?
    j
    e
    • 3
    • 3
  • i

    Ivan Đorđević

    02/17/2021, 11:40 AM
    Is there a way to still generate a "default" serializer for a class that's annotated with
    @Serialize(with = CustomSerializer::class)
    ?
    e
    • 2
    • 2
  • i

    Ivan Đorđević

    02/18/2021, 12:37 PM
    Also, would it be possible to identify types which have serializers (generated or custom)?
    e
    n
    • 3
    • 5
Powered by Linen
Title
i

Ivan Đorđević

02/18/2021, 12:37 PM
Also, would it be possible to identify types which have serializers (generated or custom)?
e

edenman

02/18/2021, 6:29 PM
might need more information on this one
if you have a
KClass
you can just call
.serializer()
but it sounds like you’re looking for something else
i

Ivan Đorđević

02/18/2021, 7:54 PM
I know I can technically do it at runtime using reflection, but I was wondering if it's possible to identify whether a type has a (custom or generated) serializer at compile time?
e

edenman

02/18/2021, 7:56 PM
not that i know of but maybe it would be helpful if you could explain more of what you’re trying to do
n

Nikky

02/19/2021, 9:48 AM
the usual pattern is to pass around the
KSerializer
instead of
KClass
there could also be multiple serializers for a single type, eg different formattings of a date into strings or numbers
View count: 6