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

    tylerwilson

    03/12/2020, 2:56 PM
    Moving here, since it appears to be related to the serialization plugin, though only for native - JVM is working fine.
    e
    • 2
    • 18
  • s

    Shan

    03/13/2020, 6:55 PM
    Hey all. I have an endpoint that's unstable (data models are changing semi-frequently without a versioning system- it's an ongoing discussion) for an application I am working on. I am using a
    Json(context = serializationContext)
    where my
    serializationContext
    is a
    SerializersModule
    which contains all of my contextual serializer mappings, to stringify/parse values, but need it to able to adapt to situations where the data model has changed server-side for older app versions that don't have an updated model. I could use
    Json.nonstrict
    for parsing/writing, but is there any way to use it with my
    serializationContext
    and have it fall back to
    nonstrict
    if the models don't match? Or is there a better way to do this that I'm missing?
    m
    • 2
    • 3
  • a

    altavir

    03/14/2020, 4:37 PM
    Hi, I am still struggling with tree-like serializers. I have following serializeable node:
    data class NodeItem<M : Meta>(val node: M) : MetaItem<M>() {
            override fun toString(): String = node.toString()
    
            @Serializer(NodeItem::class)
            companion object : KSerializer<NodeItem<out Meta>> {
                ...
            }
        }
    M
    is the recursive generics type. It is actually ignored in the serializer since we always use top type. When I use it, I get
    class hep.dataforge.meta.MetaBuilder is not registered for polymorphic serialization in the scope of class hep.dataforge.meta.Meta
    . Is it possible to somehow bypass polymorphic serializers and actually use interface type for serialization?
    • 1
    • 1
  • p

    Paulius Ruminas

    03/16/2020, 1:57 PM
    Hi, we were using
    kotlinx.serialization.internal.CommonEnumSerializer
    to serialize an enum:
    object DayTypeSerializer : CommonEnumSerializer<DayType>(
        "DayType",
        DayType.values(),
        DayType.values().map { it.type.toString() }.toTypedArray()
    )
    
    @Serializable(with = DayTypeSerializer::class)
    enum class Day(val type: Int) {
        MONDAY(1),
        TUESDAY(2),
        WEDNESDAY(3),
        THURSDAY(4),
        FRIDAY(5),
        SATURDAY(6),
        SUNDAY(7),
        HOLIDAY(8),
    }
    After 0.20.0 update
    CommonEnumSerializer
    is removed. Is there another way to achieve this?
    s
    v
    +2
    • 5
    • 6
  • n

    napperley

    03/16/2020, 11:59 PM
    Wondering how to handle a situation where a untyped JSON array (always containing two items; first item Double, second item String) is returned as part of a HTTP response body.
    d
    • 2
    • 8
  • l

    Luoqiaoyou

    03/17/2020, 3:49 AM
    Anybody ever put a jsonobject into a jsonobject? I did that because I was modifying the Java lib code. And i got error in IOS, here is detail: https://github.com/Kotlin/kotlinx.serialization/issues/759
    • 1
    • 1
  • e

    Edward Taylor

    03/22/2020, 11:39 PM
    Would anyone recommendation on how to customize/extend generated data class serializers? My json is structured like
    {
    fooProp1,
    fooProp2,
    barProp1,
    barProp2
    }
    And I'm structuring more OO in Kotlin, such as:
    data class MyThing(val prop1: String, val prop2: String)
    
    data class Combined(val foo: MyThing, val bar: MyThing)
    The data structures have a lot more repetition than shown in this example so it would be great to find something where I can take the automatically generated serializers and simply tell the combined deserializer to deserialize MyThing by prepending the name of its property name. This would probably be done in the Combined serializer, maybe giving it a modified decoder instance or something? We're wanting to target K/N in the future so want to avoid reflection, currently I'm using reflection in a custom Serializer class which iterates over the reflected object properties and uses those to figure out the keys. Any direction would be helpful, I just can't seem to figure out this usecase of wanting to extend the generated serializers, documentation or an article would help too.
    d
    • 2
    • 1
  • d

    dagomni

    03/23/2020, 5:15 PM
    Hey, does anyone know what the problem may be? Build fails and this error comes up:
    java.lang.AssertionError: org.jetbrains.kotlinx.serialization.compiler.extensions.SerializationResolveExtension caused LinkageError Caused by: java.lang.NoSuchMethodError: org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl.createWithDefaultBound(Lorg/jetbrains/kotlin/descriptors/DeclarationDescriptor;Lorg/jetbrains/kotlin/descriptors/annotations/Annotations;ZLorg/jetbrains/kotlin/types/Variance;Lorg/jetbrains/kotlin/name/Name;ILorg/jetbrains/kotlin/storage/StorageManager;)
    I'm also using Compose and its plugin, I'm mentioning it just in case it has something to do with it because I've read here and there that it could be incompatible in some cases but I don't know to what extent. Environment • Kotlin version: 1.3.61/1.3.70 • Library version: 0.14.0/0.20.0 • Kotlin platforms: JVM/Android (Multiplatform Project) • Gradle version: 6.2.1, AGP 4.1.0-alpha02 • IDE version: Android Studio 4.1.0-alpha02
    t
    • 2
    • 4
  • p

    Paul Woitaschek

    03/23/2020, 5:27 PM
    Is it possible to use serialization in kotlin scripts?
    👀 1
    • 1
    • 1
  • c

    coletz

    03/23/2020, 9:11 PM
    Posting here just cuz someone can fall in this issue (maybe me, in a week or so) and I've had some hours of pain debugging this sh*t down:
    Invalid record (Producer: 'LLVM8.0.0svn' Reader: 'LLVM APPLE_1_1100.0.33.16_0')
    . Seems like this is caused by having an inner class with Serializable annotation. My actual structure is something like a serializable data class, with an inner class which is serializable itself (and is used by the data class itself)
    e
    • 2
    • 2
  • m

    madhead

    03/24/2020, 11:59 AM
    Hello! I want to use a third-party API that expects either int or string as a value for id. Like:
    Request {
        id: int | string,
        name: string,
        // other fields
    }
    How do I do that with kotlinx.serialization? I only need to serialize my classes to JSON, no deserialization.
    s
    e
    • 3
    • 7
  • t

    thana

    03/24/2020, 2:23 PM
    i want to write a custom serializer for a
    Map<Strin, Any>
    but im struggeling how to write the descriptor for it. How do i tell the framework, that an arbitray length sequence of
    encodeString/encodeSerializableElement
    calls will follow?
    d
    • 2
    • 1
  • c

    Christian Sousa

    03/26/2020, 11:50 AM
    How can one write a custom serializer for a
    Any
    type? I’m building a data class that has a field that can either come as a
    String
    or
    List<String>
    , and I don’t have any control over that. But when I need to serialize it, it will break because of typing issues. Has anyone ever faced this issue and if yes, what’s a possible solution? (edited)
    r
    • 2
    • 6
  • g

    gabin

    03/27/2020, 11:16 AM
    Hello guys. I’m looking for a workaround for an issue https://github.com/Kotlin/kotlinx.serialization/issues/195 Lets say I have a class
    @Serializable
    data class MyUser(
        val fullName: String,
        val middleName: String? = null,
        val age: Int = 42
    )
    I want to achieve the result when following object
    MyUser("John Doe")
    will lead to json:
    {"fullName": "John Doe", age=42}
    From what I understand
    Json(encodeDefaults = false)
    will disable adding default age. Please give an advice
    m
    m
    e
    • 4
    • 7
  • s

    SrSouza

    03/30/2020, 3:12 PM
    Hi guys, I'm getting a compilation error using kotlinx.serialization in android library project. Kotlin version: 1.3.70 Kx.serialization: 0.20.0
    @Serializable
    data class IBeacon(
        override val uuid: String,
        override val major: Short,
        override val minor: Short
    ) : IBeaconFilter
    
    interface IBeaconFilter {
        val uuid: String
        val major: Short?
        val minor: Short?
    }
    Untitled
    l
    • 2
    • 1
  • j

    Jakub Pi

    03/30/2020, 4:39 PM
    I created a serializer that would allow me to cache a map containing lazy values that are expensive to compute. That way I can persist them to disk between invocations of the program:
    @Serializer(forClass = Map::class)
    class  MapWithLazyValue<K,V>(private val keySerializer : KSerializer<K>, private val valueSerializer : KSerializer<V>) : KSerializer<Map<K, Lazy<V>>> {
        override val descriptor: SerialDescriptor = PrimitiveDescriptor("map", PrimitiveKind.STRING)
    
        override fun deserialize(decoder: Decoder): Map<K, Lazy<V>> {
            return decoder.decodeSerializableValue(MapSerializer(keySerializer, valueSerializer)).mapValues { lazy { it.value } }
        }
    
        override fun serialize(encoder: Encoder, value: Map<K, Lazy<V>>) {
            encoder.encodeSerializableValue(MapSerializer(keySerializer, valueSerializer),
                value.filterValues { it.isInitialized() }.mapValues { it.value.value })
        }
    }
    However, when I try to build my project, I get:
    D:\IdeaProject\build\tmp\kapt3\stubs\main\com\collection\ArchiveHashCache.java:13: error: incompatible types: Class<MapWithLazyValue> cannot be converted to Class<? extends KSerializer<?>>
        @kotlinx.serialization.Serializable(with = com.collection.MapWithLazyValue.class)
    [WARN] Incremental annotation processing requested, but support is disabled because the following processors are not incremental: arrow.core.extensions.ExtensionProcessor (NON_INCREMENTAL), arrow.fold.AutoFoldProcessor (NON_INCREMENTAL), arrow.generic.CoproductProcessor (NON_INCREMENTAL), arrow.generic.ProductProcessor (NON_INCREMENTAL), arrow.higherkinds.HigherKindsProcessor (NON_INCREMENTAL), arrow.optics.OpticsProcessor (NON_INCREMENTAL).
    I realize this may be a bug in kapt/arrow, but have I taken the right approach to writing my custom serializer or have I done something wrong?
    • 1
    • 2
  • a

    Ahmed Mourad

    04/02/2020, 4:17 PM
    Is there any guide on how to write custom formats?
    r
    • 2
    • 13
  • m

    melatonina

    04/03/2020, 8:41 AM
    Hello. I have this class: https://gist.github.com/mel4tonin4/a8255ea412dd3f5787deefac27afce4a It's compiled just fine in Android Studio, as part of the Android application project, but when I compile it in IDEA, as part of the supporting service project, it fails with the error "@Serializable annotation is ignored because it is impossible to serialize automatically interfaces or enums. Provide serializer manually via e.g.companion object" for both the object's. In both cases I'm using
    kotlinx_serialization_runtime_version=0.14.0
    In both cases the serialization plugin is selected with
    classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
    in the top level build.gradle file where
    kotlin_version=1.3.71
    This is the build.gradle of the module that contains the class above: https://gist.github.com/mel4tonin4/9bf05d82f8901613b131998162250495 What's the reason for this difference?
    t
    • 2
    • 24
  • c

    crummy

    04/04/2020, 9:52 PM
    I'm querying Google Sheets and am not quite sure how to build an object to deserialize this:
    {
      "values": [
        [
          "Plums",
          5
        ],
        [
          "Apples"
          4
        ]
      ]
    }
    If the quantities were strings I'd do
    values: List<List<String>>
    but this fails with
    Expected string literal
    . Can I do this?
    t
    p
    s
    • 4
    • 17
  • k

    Kiryushin Andrey

    04/07/2020, 11:18 AM
    Hi, is there any workaround to use inline classes with kotlinx-serialization now? I tried to implement custom serializer, but the compiler still doesn't allow me to mark inline class as serializable
    m
    • 2
    • 2
  • i

    Ivan Brko

    04/08/2020, 1:37 PM
    Hi all. I'm learning kotlinx.serialization and I have a question Let's say I have a data class like this:
    data class Data(val a: String, val b: String)
    Now, I know I could add @Serializable and have everything generated for me. But what if I can't annotate this class, it is not in my code? Do i need to write the serialization manually or is there a way to automatically generate KSerializer for it?
    t
    g
    • 3
    • 5
  • f

    fkrauthan

    04/08/2020, 4:55 PM
    Anyone knows when the next release is planned for?
    d
    • 2
    • 5
  • s

    Sam Garfinkel

    04/08/2020, 9:34 PM
    Is there an overview of all functions that the compiler will generate for Serializable classes? I’d like to use a DI framework to inject some dependencies into the deserialized data class so I’d probably want to wrap the generated serializer in another serializer that is capable of receiving the injected types. Also does using
    @Serializable(with=Foo::class)
    where
    Foo
    is initialized at runtime work? Or do I need to use a ContextualSerializer in this case?
    d
    • 2
    • 1
  • s

    Sean Keane

    04/09/2020, 1:49 PM
    Hi All, I seem to have an issue with parsing Enums. I used to use
    kotlinx.serialization.internal.CommonEnumSerializer
    but it doesnt seem to be available anymore? Am I missing something?
    d
    • 2
    • 2
  • s

    Sam Garfinkel

    04/09/2020, 2:58 PM
    Does using
    @Serializable(with=SomeSerializer::class)
    still cause a default serializer to be generated?
    d
    • 2
    • 1
  • d

    diego-gomez-olvera

    04/10/2020, 8:36 AM
    Hello everyone! I am experimenting with Protocol Buffers now https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/examples.md#user-defined-serial-annotations and I was wondering if it would be possible to get the schemas from
    @Serializable
    entities
    • 1
    • 2
  • i

    Ivan Brko

    04/10/2020, 10:31 AM
    Hi all, I have the following issue and I would be grateful if someone could point me in the right direction. I am using kotlinx.serialization in KMongo (org.litote.kmongo:kmongo-coroutine-serialization:3.12.2) I have the following data class which is in a file I cannot edit:
    data class User(
        val username: String,
        val email: String,
        val firstName: String,
        val lastName: String,
        val password: String,
        val role: Role,
        val createdAt: LocalDateTime,
        val updatedAt: LocalDateTime
    )
    So, in my file I create a serializer for it like this:
    @Serializer(forClass = User::class)
    object UserSerializer {}
    Now, everything seems to work OK when deserializing the data, however when KMongo tries to serialize it and send it to DB, I get a nasty java exception stack with the following message:
    java.lang.IndexOutOfBoundsException: com.example.domain.users.User descriptor has only 8 elements, index: 0
    After going through code, I found that in file PluginGeneratedSerialDescriptor.kt there is an overriden fun getElementDescriptor in which property generatedSerializer is trying to get accessed, but it is null and this causes the exception. Does anyone know if this is a bug, or I'm doing something wrong here?
    d
    • 2
    • 2
  • l

    Lamberto Basti

    04/10/2020, 2:40 PM
    Hi! Say you have:
    @Serializable
    data class PagedData<T>(val data: T, val page: Int, val totalPages: Int, val pageSize: Int)
    Where you know for sure that
    T
    is a class that has the annotations
    @Serializable
    or a list of a type that is annotated with
    @Serializable
    . Why the serialization runtime is not able to infer what to use? Also, I am using Ktor, it would be kind of pointless to explicitly build a serializer before every response as such.
    ⬆️ 1
    d
    • 2
    • 9
  • a

    altavir

    04/10/2020, 5:48 PM
    SerialDescriptor.withName is deprecated. What should I do not if I want to use a MapSerializer for another class. Should I leave the name as is?
    d
    • 2
    • 8
  • a

    altavir

    04/11/2020, 12:05 PM
    Another question about map serialization. I have a map with polymorphic value type and I have serializer module for it. How can I construct a serializer for the map to use in custom serializer?
    d
    • 2
    • 3
Powered by Linen
Title
a

altavir

04/11/2020, 12:05 PM
Another question about map serialization. I have a map with polymorphic value type and I have serializer module for it. How can I construct a serializer for the map to use in custom serializer?
d

Dominaezzz

04/11/2020, 3:18 PM
MapSerializer(String.serializer(), PolymorphicSerializer(YourClass::class))
?
🙏 1
➕ 1
a

altavir

04/11/2020, 4:54 PM
Wow, looks simple, let me try it.
Seems to be working, thanks @Dominaezzz
👍🏼 1
View count: 8