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

    uhe

    05/06/2019, 3:16 PM
    Suppose I have a JSON string like this:
    [36, {"color": "orange", "sizes": [23, 42, 7]}]
    (so a mixed JSON array) where the first entry of the array is always an
    Int
    that represents a type of message and the second is an arbitrary map payload. I, as a library, need to parse the type field to do some things, but I don't care about the payload and would like to deserialize into a type that is provided by my users. E.g.
    fun <UserType> parseMessage(json: String): UserType
    Can this be done via kotlinx serialization?
    • 1
    • 4
  • y

    yshrsmz

    05/07/2019, 9:04 AM
    @Serializable
    data class UserProfile(val id:String)
    
    fun test() {
      val jsonElement = Json.nonstrict.toJson<UserProfile?>(NullableSerializer(UserProfile.serializer()), null)
      println("jsonElement: $jsonElement")
    }
    Above code throws following error in kotlin 1.3.31 x serialization 1.1.0.
    Caused by: kotlinx.serialization.SerializationException: No tag in stack for requested element
            at kotlinx.serialization.TaggedEncoder.popTag(Tagged.kt:160)
            at kotlinx.serialization.TaggedEncoder.encodeNull(Tagged.kt:92)
            at kotlinx.serialization.internal.NullableSerializer.serialize(NullableSerializer.kt:39)
            at kotlinx.serialization.json.internal.AbstractJsonTreeOutput.encodeSerializableValue(TreeJsonOutput.kt:174)
            at kotlinx.serialization.CoreKt.encode(Core.kt:73)
            at kotlinx.serialization.json.internal.TreeJsonOutputKt.writeJson(TreeJsonOutput.kt:29)
            at kotlinx.serialization.json.Json.toJson(Json.kt:129)
    has anyone experienced this issue?
    s
    • 2
    • 3
  • e

    efemoney

    05/12/2019, 9:20 PM
    How does one use the polymorphic stuff for sealed class heirarchies? Can I get away with only annotating my sealed BaseClass with
    @Polymorphic
    ?
    i
    • 2
    • 2
  • t

    thana

    05/15/2019, 4:07 PM
    is there a way to get the code of the generated de/serrializers?
    • 1
    • 1
  • t

    thana

    05/15/2019, 7:23 PM
    does anybody know what the
    SerialDescriptor
    generated for a
    @Serializable
    class depends on?
    s
    r
    h
    • 4
    • 18
  • t

    tylerwilson

    05/16/2019, 1:38 PM
    Good day. I am working with an API that varies how dates are encoded. So I would like to do something like this:
    @DateSerializer(format="MM-dd-YYYY")
    var date1: Date
    Is this possible with Kotlin Serialization (multiplatform)? Any examples anybody might be able to throw my way? Thank you!
    s
    • 2
    • 3
  • s

    serebit

    05/17/2019, 6:55 PM
    Will the serialization plugin and runtime be published to the Gradle plugin portal and jcenter respectively once they exit experimental status?
    s
    • 2
    • 1
  • j

    jeremy

    05/19/2019, 4:47 PM
    What is best way to integrate kotlinx serialization+ktor client in a MPP? The only resource I could find is : https://ktor.io/clients/http-client/features/json-feature.html which refers to using a JVM dependency
    s
    r
    +2
    • 5
    • 10
  • p

    Paul Woitaschek

    05/20/2019, 12:44 PM
    Is it possible to inject a serializer? For example I have a data class in my gradle module
    x
    . It has a
    UUID
    and the
    KSerializer<UUID>
    lives in gradle module
    y
    . My module
    x
    doesn't know anything about my module
    y
    . Now I would like to inject that UUIDSerializer instance. Is that possible?
    t
    s
    • 3
    • 9
  • j

    jeremy

    05/20/2019, 11:56 PM
    ktor_serialization_.txt
    r
    j
    s
    • 4
    • 20
  • n

    Nikky

    05/24/2019, 12:54 PM
    are enums still broken? marking one as
    @Serializable
    seems to break everything
    s
    • 2
    • 5
  • m

    Marc Knaup

    05/25/2019, 3:56 PM
    Don't enums have a
    .serializer()
    function by default?
    s
    • 2
    • 3
  • a

    altavir

    05/25/2019, 5:58 PM
    Hello, guys. I am currently making a simple tornadofx GUI to generate a XML configuration. I believer that in order to do so, the simplest way is to make my model classes seializable and use @pdvrieze's xmlutil and make my model classes seializable. In order to do so, I need to create custom serializators for javafx Properties. Like this:
    @Serializer(forClass = StringProperty::class)
    object StringPropertySerializer : KSerializer<StringProperty> {
    
        override val descriptor: SerialDescriptor = StringDescriptor
    
        override fun serialize(encoder: Encoder, obj: StringProperty) {
            encoder.encodeString(obj.value)
        }
    
        override fun deserialize(decoder: Decoder): StringProperty {
            return SimpleStringProperty(decoder.decodeString())
        }
    }
    I have two questions: 1. The property is nullable, how can I create a descriptor for nullable value. In @pdvrieze's code there is a delegate wrapper that copies descriptor functionality and switches the
    nullable
    flag. Is i the best way to do so. Do I even need the flag 2. Serialized xml seems to have class names for tag names instead of names of the peoperties. Is it something in serializaition, or a feature of
    xmlutil
    ? 3. How can I tell enums to be serializaed into their names. Do I need custom serialized for that?
    s
    • 2
    • 2
  • m

    Marc Knaup

    05/26/2019, 12:25 AM
    Can't a
    KSerializer
    do some look-ahead for the next token type when reading something? E.g. • if next token is string then decode as A • if next token is object then decode as B
    s
    • 2
    • 6
  • m

    Marc Knaup

    05/26/2019, 12:26 AM
    -- And
    kotlinx-serialization-runtime-native
    0.11.0
    isn't compatible with Kotlin 1.3.40-eap 😕
    w: skipping /Users/marc/.gradle/caches/modules-2/files-2.1/org.jetbrains.kotlinx/kotlinx-serialization-runtime-native_debug_ios_x64/0.11.0/c80bda43e7d80430654f2ef709df51a073ed0f0e/kotlinx-serialization-runtime-native.klib. The abi versions don't match. Expected '[9]', found '8'
    w: The compiler versions don't match either. Expected '[1.3]', found '1.2-release-9411'
    i
    s
    • 3
    • 5
  • a

    altavir

    05/26/2019, 9:01 AM
    Functions are basically non-serializable. You should use SAM classes or method references for that.
    h
    • 2
    • 2
  • p

    Paul Woitaschek

    05/27/2019, 2:52 PM
    The kdoc of
    Json.parse
    states:
    /**
         * Deserializes given json [string] into a corresponding object of type [T] using provided [deserializer].
         * @throws [JsonException] subclass in case of serialization error.
         */
    However upon missing field it throws a
    kotlinx.serialization.MissingFieldException
    . Is this a known issue?
    n
    m
    • 3
    • 7
  • s

    sandwwraith

    05/29/2019, 2:35 PM
    Sealed classes now do not have any special support, so you should use the same approach as if you were using regular polymorphic serialization (
    @Polymorphic
    annotation, SerializersModule, etc). We have plans to improve it in future.
    p
    • 2
    • 11
  • a

    Antanas A.

    05/31/2019, 7:08 AM
    Hello, I've just updated serialization library from 0.10.0 to 0.11.0 and now getting error: Unresolved reference: registerSerializer and Classifier 'PolymorphicSerializer' does not have a companion object, and thus must be initialized here
    // * We need to register serializers for this RequestForChangeEvent to allow proper serialization for this type
        companion object {
            init {
                registerSerializer(RequestForChangeEvent::class.java.name, RequestForChangeEvent.serializer(PolymorphicSerializer))
                registerSerializer(ChangeRejectedEvent::class.java.name, ChangeRejectedEvent.serializer(PolymorphicSerializer))
                registerSerializer(ChangeAcceptedEvent::class.java.name, ChangeAcceptedEvent.serializer(PolymorphicSerializer))
            }
        }
    how can I fix this?
    s
    p
    • 3
    • 34
  • a

    Antanas A.

    05/31/2019, 1:03 PM
    Got compiler error when tried to compile:
    @Serializable
    interface EventData
    error:
    e: java.lang.IllegalStateException: Backend Internal error: Exception during code generation
    Cause: Back-end (JVM) Internal error: @Serializable annotation on class EventData would be ignored because it is impossible to serialize it automatically. Provide serializer manually via e.g. companion object
    This interface will be used as a marker interface and it will be used on data class X(...) : EventData
    s
    • 2
    • 5
  • t

    thana

    05/31/2019, 1:04 PM
    what's the
    @SerialId
    used for protobuf good for? are there any hints about how it should be used?
    s
    • 2
    • 5
  • t

    thana

    05/31/2019, 2:08 PM
    well.
    null
    is not supported with protobuf. that is a HUGE drawback
    s
    • 2
    • 8
  • m

    Marc Knaup

    06/02/2019, 11:21 PM
    Why do I get
    ISE: Class Duration have constructor parameters which are not properties and therefore it is not serializable automatically
    When I specify
    @Serializable(with = DurationSerializer::class)
    and a matching
    @Serializer(forClass = Duration::class)
    ? There shouldn't be automatic serialization. EDIT: oh wow, it happens when I "half-specify" a serializer. I had
    deserialize
    and
    serialize
    but not
    descriptor
    . Kinda unexpected that if you create a custom serializer it generates a descriptor automatically based on the constructor which may be a total mismatch with what my serializer actually does 🤔 Is that intentional?
    s
    • 2
    • 1
  • m

    m

    06/04/2019, 11:15 AM
    Hi. Could you please advice how to fix
    [Exception] class kotlin.String is not registered for polymorphic serialization in the scope of class kotlin.CharSequence class kotlinx.serialization.SerializationException
    error?
    s
    • 2
    • 3
  • b

    bjonnh

    06/04/2019, 11:12 PM
    @charleskorn Any idea how I can solve that: https://github.com/charleskorn/kaml/issues/1
    ✔️ 1
    c
    s
    • 3
    • 6
  • t

    Toddobryan

    06/06/2019, 5:49 PM
    What's the best way to report doc issues? I found some links to files that no longer exist and docs that don't seem to be valid anymore.
    s
    • 2
    • 1
  • p

    Paulius Ruminas

    06/08/2019, 11:05 AM
    Hi, is it possible to configure the serializer to use simple class name instead of qualified class name for polymorphic serialization type field or do I have to write a custom serializer to achieve this?
    s
    • 2
    • 3
  • p

    Paulius Ruminas

    06/08/2019, 8:12 PM
    Does polymorphic serializer support sub classes with generic type parameters?
    @Serializable
    sealed class Foo<T : Any> {
        @Serializable
        data class Bar<T : Any>(val o: T) : Foo<T>()
    
        @Serializable
        data class Baz(val o: String) : Foo<String>()
    }
    It's not possible to do something like
    PolymorphicSerializer(Foo::class, UnitSerializer)
    .
    s
    • 2
    • 6
  • m

    Marc Knaup

    06/09/2019, 12:46 PM
    Why do example serializer implementations use
    lateinit
    for required properties? That will just throw an
    UninitializedPropertyAccessException
    at runtime if the property is missing during deserialization instead of the expected
    SerializationException
    . Due to the examples I've assumed that such a case can never happen because the descriptor states that these properties are mandatory and it would be checked internally. Doesn't seem to be the case though 😞
    s
    • 2
    • 3
  • n

    Nikky

    06/09/2019, 9:32 PM
    seems like readding
    @Optional
    fixes it , but its marked as deprecated and all crossed out
    s
    l
    • 3
    • 5
Powered by Linen
Title
n

Nikky

06/09/2019, 9:32 PM
seems like readding
@Optional
fixes it , but its marked as deprecated and all crossed out
s

sandwwraith

06/10/2019, 10:00 AM
Probably you use old version of Kotlin compiler with the new version of library?
n

Nikky

06/11/2019, 9:51 AM
i was using 1.3.31, is there an newer version thats not eap ?
l

louiscad

06/11/2019, 11:14 AM
The serialization gradle plugin is also set to 1.3.31?
n

Nikky

06/11/2019, 11:51 AM
yes
s

sandwwraith

06/11/2019, 12:20 PM
It should work with 1.3.31. Probably old version stuck somewhere in cache or other buildscripts
View count: 3