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

    jakiej

    10/22/2018, 4:21 PM
    I have a class that is used to be serialized to Json without problems with kotlin 1.2 (0.6.2 with no customized serializers). after migrating to 1.3 (0.8,3), it stopped working, complaining about either some enum class or java singletonMap can't be serialized. is this expected? I don't see any mentioning about backward imcompatibility in the 1.3 doc.
    s
    • 2
    • 4
  • j

    jcechace

    10/22/2018, 8:36 PM
    Another one. I have a java class which consist mainly of primitive properties (lets assume only from primitive properties). Do I really have to write a serializer which contains something like
    val json = JsonObject(mapOf(
                "apiId" to JsonPrimitive(obj.apiId),
                "organizationId" to JsonPrimitive(obj.organizationId),
    //            .... endless ...
            ))
    • 1
    • 1
  • c

    coletz

    10/25/2018, 7:41 PM
    Am I the only one having problems with MyObject.serializer()? It stopped working after an update (not sure which, I'm checking now) and now I only have MyObject::class.serializer()
    t
    • 2
    • 5
  • j

    jkbbwr

    10/26/2018, 1:51 AM
    Is there a simple gradle kts dsl example I can't figure this out
    g
    n
    • 3
    • 16
  • g

    gildor

    10/26/2018, 5:18 AM
    What is the most efficient and correct way to check that some class can be serialized/deserilized using kotlinx.serialization Of course for simple cases you can check presence of annotations using reflectsions (also would be good to avoid, at least provide some conventional way). What about complicated ones (external serializers etc)? My use case that I would like to adopt kotlinx.serialization but we have a lot of existing data modesl and use Gson for Json mapping, so it would be hard to migrate everything at the same time I’m looking for some migration strategy, one of them to use Gson only as fallback during migration phase
    s
    • 2
    • 1
  • j

    jdemeulenaere

    10/26/2018, 9:17 PM
    Is there any advanced doc on writing custom KSerializer ?
    t
    • 2
    • 2
  • c

    coletz

    10/27/2018, 10:06 PM
    Kotlin serialization support consists of three parts: a compiler plugin, which produces visitor/serializer code for objects, an IntelliJ plugin and a runtime library.
    Are intellij plugin and compiler plugin open source? I can't find them on github
    s
    • 2
    • 2
  • k

    k_marussy

    10/28/2018, 12:08 PM
    Is there any way for Jackson-style
    As.PROPERTY
    polymoprhic deserialization (e.g.,
    {"type": "some.class.Name", "property": "value"}
    instead of
    ["some.class.Name", {"property": "value"}]
    ) with kotlinx.serialization? I actually have some even more polymorphic gnarly (de)serailization requirements, which I could handle by some pretty ugly custom Jackson (de)serializers, but I would be interested a JVM-idependent solution. A key idea seems to be some kind of lookahead, during which Jackson can put tokens into a
    TokenBuffer
    while searching for the
    "type"
    attribute, and prefix the remaining token stream with the buffer contents upon calling the concrete deserializer. As the JSON schema I have to handle clearly wasn't designed with ease of parsing in mind, I have to rely a lot on lookahead. I am unsure how to achieve something similar with
    KInput
    and
    KSerialClassDesc
    .
    ➕ 1
    s
    t
    • 3
    • 9
  • t

    thevery

    10/29/2018, 3:52 PM
    What serialization version should be used for 1.3 release - 0.9.0?
    s
    • 2
    • 1
  • n

    Nikky

    10/30/2018, 1:17 AM
    so this is outdated ? https://github.com/Kotlin/kotlinx.serialization#gradlejvm
    j
    • 2
    • 1
  • n

    Nikky

    10/30/2018, 1:24 AM
    @jasoet so yes you do need that.. see the stuff i linked for the settings.gradle.kts configuration that allows you to just apply it in a
    plugins
    block
    j
    • 2
    • 1
  • j

    jw

    10/30/2018, 1:25 AM
    that kts is scary... is that how normal people are supposed to use it?
    g
    • 2
    • 2
  • k

    Ken

    10/30/2018, 6:00 PM
    Sorry if this isn't the correct channel for this question. I attempted to upgrade to Kotlin 1.3. I had been using Kotlinx Serialization 0.6.2 and its associated plugins for Maven and Intellij. When I attempted to build, the compiler errors out on the @Serializable annotation with: java.lang.IllegalStateException: Backend Internal error: Exception during code generation Cause: org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl.initialize(Lorg/jetbrains/kotlin/types/KotlinType;Lorg/jetbrains/kotlin/descriptors/ReceiverParameterDescriptor;Ljava/util/List;Ljava/util/List;Lorg/jetbrains/kotlin/types/KotlinType;Lorg/jetbrains/kotlin/descriptors/Modality;Lorg/jetbrains/kotlin/descriptors/Visibility;)Lorg/jetbrains/kotlin/descriptors/impl/SimpleFunctionDescriptorImpl; I removed the Kotlinx plugin from Maven pom, and rebuilt the compile succeeds but my unit test fail with the exception: kotlinx.serialization.SerializationException: Can't locate default serializer for class <myclass> I then tried by upgrading to Kotlinx Serializer 0.9.0, but the signature fo kotlinx.serialization.json.JSON.stringify and parse have change to require a Serializer as its first argument and the @ImplicitReflectionSerializer annotations for all clients - this change doesn't seem to be documented anywhere and for me has major implications. I have to ask all my clients to add @ImplicitReflectionSerializer before using my library methods. Is there a better way to handle this change. It seems like a "breaking" change that should have been called out and documented. Here is my code with the issue, wondering if Generics is contributing to the issue: inline fun <reified T: Any> parseToClass(jsonResponse: String): T { try { return JSON.nonstrict.parse<T>(jsonResponse) } catch(ex: Exception) { Logger.error("Failed to parse JSON to class ${T::class.simpleName}", ex) throw ex } }
    s
    • 2
    • 2
  • j

    josephivie

    10/31/2018, 5:12 PM
    Never mind, it's just that you can't use the IDE's run button in the gutter to run the tests. They must be done through gradle.
    t
    • 2
    • 1
  • n

    Nikky

    11/01/2018, 9:37 PM
    https://github.com/Kotlin/kotlinx.serialization#gradlejvm this sample refers to
    kotlin-serialization
    , was the plugin renamed ?
    s
    • 2
    • 1
  • j

    jakiej

    11/02/2018, 12:10 AM
    Hi, I am trying to maintain some backward compatibility to serialized JSON: for example
    {
      "a": {
        "b": "c"
      }
    }
    to
    @Serializable
    class Wrapper(val a: Map<String, Any> = mapOf())
    what's the easiest way? (if there a way I can specify default (e.g,
    LinkedHashMap
    ) for Map and default (
    String
    ) for "c"?
    s
    • 2
    • 13
  • n

    Nikky

    11/02/2018, 10:42 AM
    so with 0.9.0 i cannot longer just rely on implicit reflection and use
    JSON.stringify(something)
    for now i solved it like this
    data class Something(
        val someProperty: String
    ) {
        @Serializer(forClass=Something::class)
        companion object
    }
    
    JSON.parse(Something, string)
    is there a better way than adding companion objects to everything ?
    s
    • 2
    • 7
  • n

    Nikky

    11/06/2018, 6:15 PM
    <http://logger.info|logger.info>("loading configuration")
    
            val rootFolder = File(".").absoluteFile
            val configFolder = rootFolder.resolve("config")
            configFolder.mkdirs()
    
            val baseFile = configFolder.resolve("base.hocon")
    
            val parser = ConfigParser()
    
            val config = ConfigFactory.parseFile(baseFile)
            println(config)
            val baseConfig = parser.parse(config, BaseConfiguration.serializer())
    
            println(baseConfig)
    BaseConfiguration is
    @Serializable
    data class BaseConfiguration (
        @Optional var ids: List<Int> = listOf(),
        @Optional var strings: List<String> = listOf()
    )
    s
    • 2
    • 2
  • n

    Nikky

    11/06/2018, 6:35 PM
    @sandwwraith there seems to be no
    stringify
    for typesafe config, is that some limitation of the urrent codegeneration done by kotlinx or did nobody got around to implement that yet ?
    s
    • 2
    • 1
  • s

    sandwwraith

    11/14/2018, 11:43 AM
    Maybe a typo somewhere? Any differences from this pom? https://github.com/Kotlin/kotlinx.serialization/blob/master/example-jvm/pom.xml
    v
    • 2
    • 24
  • t

    Tasos Stamadianos

    11/26/2018, 6:17 PM
    hi all, i have a somewhat complex use case for serialization for messages being communicated around a distributed system. The messages come in like so:
    {
    	"sessionId": "...",
    	"commandId": "...",
    	"message": { ... }
    }
    So, at a lower layer of my code, I parse the
    sessionId
    and the
    commandId
    using
    JsonTreeParser
    , and using the same parser I extract
    message
    as a JsonObject. Later on, whoever needs to use the
    message
    JsonObject can deserialize to whatever they want using
    mapper.readTree
    . Now, say I need to serialize back to another format. Specifically:
    {
    	"success": true,
    	"message": "...",
    	"commandId": "...",
    	"payload": { ... }
    }
    That
    payload
    field is any custom class which needs to be serializable and passed somehow, but I can't find a way to make it a JsonObject, or write any JsonObject for that matter. I also tried making a generic class with an field of the type of
    payload
    , but that didn't seem like the right direction. I guess what I'm asking is, how can I create a JsonObject from an instance of a class?
    s
    • 2
    • 15
  • t

    thevery

    11/29/2018, 4:52 PM
    What is the status for
    encodeDefaults
    and JSON serializer? This case doesn't work for me:
    @Serializable data class N(val s: String, val l: List<Int>? = null)
            assertEquals("""{"s":"s"}""", JSON(encodeDefaults = false).stringify(N.serializer(), N("s")))
    s
    • 2
    • 5
  • b

    bartvh

    11/30/2018, 2:08 PM
    I'm trying to get a long field to encode as a string instead of as a number in JSON (for values that overflow double):
    @Serializer(forClass = Long::class)
    object LongStrSerializer : KSerializer<Long> {
        override fun deserialize(input: Decoder): Long =
                input.decodeString().toLong()
    
        override fun serialize(output: Encoder, obj: Long) =
                output.encodeString(obj.toString())
    }
    
    @kotlinx.serialization.Serializable
    data class PlayerSummary(
            @kotlinx.serialization.Serializable(with = LongStrSerializer::class)
            val id: Long,
            val displayName: String
    )
    However this still results in:
    {
      "displayName": "Jessie James",
      "id": 1337000000
    }
    What am I doing wrong?
    s
    • 2
    • 2
  • a

    adev_one

    12/06/2018, 7:36 AM
    Is there way to deserialize
    JsonElemet
    as field of
    @Serializable
    class? Example:
    @Serializable
    data class Test(
        val a: Int,
        val b: JsonElement
    )
    
    val test = JSON.parse(Test.serializer(), """{"a":1,"b":{"test":"test2"}}""")
    println(test.toString())
    s
    • 2
    • 2
  • l

    Lulu

    12/12/2018, 9:28 AM
    How to debug this:
    kotlinx.serialization.json.JsonParsingException: Invalid JSON at 1221: Expected '[, kind: kotlinx.serialization.UnionKind$POLYMORPHIC@1e6d1014'
    s
    n
    • 3
    • 5
  • t

    thevery

    12/13/2018, 9:55 AM
    @sandwwraith is there any version for 1.3.20?
    s
    n
    • 3
    • 3
  • l

    Lulu

    12/13/2018, 11:04 AM
    Is it possible to serialize a field that can be either boolean or Double? (No it's not my API, I wouldn't have designed it that way)
    s
    • 2
    • 2
  • h

    hallvard

    12/13/2018, 3:42 PM
    I did believe it should be faster, as the different fields are identified during compilation and no reflection should be needed in runtime. I may be wrong though. Could someone else shed some light here?
    t
    • 2
    • 1
  • c

    charleskorn

    12/17/2018, 2:29 AM
    I’ve created a very basic library to add support for YAML to kotlinx.serialization: kaml It’s very limited at the moment (it only supports deserialisation) and is very, very rough (I’ve taken a bunch of shortcuts that will hurt performance, and there are a bunch of error messages that aren’t great), but I’d love any feedback, suggestions or contributions you might have 🙂 More details: https://github.com/charleskorn/kaml
    👍 7
    g
    • 2
    • 1
  • s

    sandwwraith

    12/20/2018, 3:19 PM
    📣 Serialization v
    0.10.0-eap-1
    (dev branch) has just been released! This is a companion release to Kotlin
    1.3.20-eap-52
    Highlights: • Now Native plugin supports generics, @SerialInfo annotations and other features that were missing before • Now
    SerialDescriptor.getElementDescriptor
    is working and one can use it to deeply inspect descriptors tree • JSON now can omit default values • (breaking change) Context serializer is not enabled automatically anymore, use
    @ContextualSerialization
    on property. Full changelog: https://github.com/Kotlin/kotlinx.serialization/blob/dev/CHANGELOG.md
    🔥 1
    🎉 10
    ♥️ 1
    j
    • 2
    • 2
Powered by Linen
Title
s

sandwwraith

12/20/2018, 3:19 PM
📣 Serialization v
0.10.0-eap-1
(dev branch) has just been released! This is a companion release to Kotlin
1.3.20-eap-52
Highlights: • Now Native plugin supports generics, @SerialInfo annotations and other features that were missing before • Now
SerialDescriptor.getElementDescriptor
is working and one can use it to deeply inspect descriptors tree • JSON now can omit default values • (breaking change) Context serializer is not enabled automatically anymore, use
@ContextualSerialization
on property. Full changelog: https://github.com/Kotlin/kotlinx.serialization/blob/dev/CHANGELOG.md
🔥 1
🎉 10
♥️ 1
j

Jonas Bark

12/20/2018, 4:03 PM
regarding the "omit default values": when I have a simple class like this: @Serializable data class Test(val name: String? = null) then Json(encodeDefaults = false).stringify(Test.serializer(), testInstance) should print out "{}"? This doesn't seem to work for me
got it - name needs to have @Optional. The documentation of @Optional got me confused 🙂
View count: 2