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

    Dariusz Kuc

    07/21/2022, 5:38 PM
    Hello 👋 Any suggestions on how one would go around debugging
    org.jetbrains.kotlin.util.KotlinFrontEndException: Front-end Internal error: Failed to analyze declaration Variables
    File being compiled: (35,3) in <Foo.kt>
    The root cause java.lang.AssertionError was thrown at: org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor.getModality(LazyClassDescriptor.java:564)
    ...
    Caused by: java.lang.AssertionError: Recursion detected in a lazy value under LockBasedStorageManager@2f5a443e (TopDownAnalyzer for JVM)
    a
    6 replies · 2 participants
  • r

    Remo

    07/23/2022, 1:32 PM
    Hi there! Facing troubles with Serialization… Could someone explain me what’s wrong and what I need to do? Using serialization 1.6.10…
    sealed interface Convertible {
    
        fun convertUserInput(value : String): String
    }
    
    
    @Serializable
    @SerialName("CustomConvertible")
    class CustomConvertible(): Convertible {
    
    
        override fun convertUserInput(value : String): String {
           return ""
        }
    }
    
    
    @Serializable
    class DTOAttribute(val convertibles         : List<Convertible>   = emptyList())
    Later on, I’d like to encode the
    DTOAttribute
    with
    val string = Json.encodeToString(dtoAttr)
    Calling this, gives me the following exception:
    kotlinx.serialization.SerializationException: Class 'CustomConvertible' is not registered for polymorphic serialization in the scope of 'Convertible'.
    Mark the base class as 'sealed' or register the serializer explicitly.
    What am I doing wrong?
    e
    3 replies · 2 participants
  • m

    mytrile

    07/24/2022, 5:48 PM
    Hi, could someone explain to me why I'm still getting "kotlinx.serialization.SerializationException: Serializer for class 'Project' is not found. Mark the class as @Serializable or provide the serializer explicitly." even if the class is annoted, literally using the 2 line example from https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#json-decoding
    a
    3 replies · 2 participants
  • m

    MR3Y

    07/26/2022, 9:02 PM
    Is it possible to deserialize only a fragment of the Json response?. For example, if I have a Json response like this:
    {
      "responseHeader": {
        "a": 0,
        "b": 407,
        "c": {
             ....
        }
      },
      "response": {
        "numFound": 2,
        "start": 0,
        "docs": [
          {
            "foo": "foo",
            "bar": "bar"
          },
          {
            "foo": "foo",
            "bar": "bar"
          }
        ]
      },
      "unimportant": {
        "unimportant": []
      }
    }
    I'm interested only in the
    response
    part, so, Instead of deserializing the entire response, I want to just deserialize this part. is this possible with kotlinx.serialization? Of course I can deserialize the whole response & get rid of the irrelevant parts on the client side, but this would be a waste of time. So, it would be nice if there is a built-in way to do this.
    e
    3 replies · 2 participants
  • a

    alllex

    07/27/2022, 7:58 AM
    I am at a loss trying to configure serialization of generics. I have a pretty simple setup:
    import kotlinx.serialization.*
    import kotlinx.serialization.json.Json
    
    @Serializable
    sealed class ApiResponse<T> {
        @Serializable
        @SerialName("result")
        data class Ok<T>(val result: T) : ApiResponse<T>()
    
        @Serializable
        @SerialName("error")
        data class Error<T>(val error: ErrorResponse) : ApiResponse<T>()
    }
    
    @Serializable
    data class VersionResponse(val version: String)
    
    @Serializable
    data class ErrorResponse(val description: String)
    
    fun main() {
        val data: ApiResponse<VersionResponse> = ApiResponse.Ok(VersionResponse("v42"))
        println(Json.encodeToString(data)) // prints {"type":"result","result":{"version":"v42"}}
    }
    The last line mentions the result I want to achieve:
    ApiResponse
    is discriminated using
    type
    , and the
    result
    field is just serialized as it is. However, running this with Kotlin 1.7.10 and kotlinx.serialization 1.3.3 (json jvm) produces this error:
    Exception in thread "main" kotlinx.serialization.SerializationException: Class 'VersionResponse' is not registered for polymorphic serialization in the scope of 'Any'.
    Mark the base class as 'sealed' or register the serializer explicitly.
    	at kotlinx.serialization.internal.AbstractPolymorphicSerializerKt.throwSubtypeNotRegistered(AbstractPolymorphicSerializer.kt:102)
    Could you please help figuring this out? I tried in many ways to configure polymorphic serialization, but none of them worked.
    r
    5 replies · 2 participants
  • v

    vqrs

    07/28/2022, 3:48 PM
    bump https://kotlinlang.slack.com/archives/C7A1U5PTM/p1658261294261379?thread_ts=1658261294.261379&amp;cid=C7A1U5PTM
    l
    c
    4 replies · 3 participants
  • v

    Vampire

    07/11/2022, 2:02 AM
    I want to port the custom serializer at https://github.com/Vampire/setup-wsl/blob/master/buildSrc/src/main/kotlin/net/kautler/dao/GitHubAction.kt#L73 that still runs on 0.20.0 to 1.3.x. I there have used
    override val descriptor = SerialDescriptor("...", CONTEXTUAL)
    for the
    KSerializer
    . How would I port that to 1.3.x as the function does not expect a kind anymore?
    s
    e
    11 replies · 3 participants
  • c

    cb

    07/29/2022, 9:33 AM
    We're currently using Serialization (1.3.2, but trying 1.3.3 and 1.4 now) for serializing some very simple objects into JSON (they're basically Android navigation holders). We use these classes a lot. They're used for all navigation calls in our Android app, and get serialized at each
    navigate()
    , therefore performance is important. Most of these
    Args
    classes we have are
    @Serializable object MyScreenArgs: ArgsInterface
    , and some are data classes if they contain some inner values. We've seen that creating a
    serializer()
    for the
    object
    classes is extremely slow:
    7,137ns   benchmarkDataClassContentViewArgsToBundle
    69,204ns  benchmarkObjectContentViewArgsToBundle
    5,301ns   benchmarkDataClassBundleToContentViewArgs
    67,981ns  benchmarkObjectBundleToContentViewArgs
    (tests using AndroidX Microbenchmark on a Google Pixel 1) It doesn't matter if we use the reflection or non-reflection versions of
    serializer()
    , they're both very similar in terms of time. In fact, the generated serializer is usually slightly slower to retrieve for some reason. I've profiled our tests, and 90% of the time is spent retrieving the
    serializer()
    , the conversion to/from JSON is around 3ms for all benchmarks. Anyone know why the object serializer could be so slow?
    m
    4 replies · 2 participants
  • y

    y9san9

    08/02/2022, 1:30 PM
    Hey! Just wonder if someone could help with this issue: https://youtrack.jetbrains.com/issue/KT-53437/External-serializer-does-not-work-properly-with-multiple-modules My friend stuck with it 😢
  • j

    joschi

    08/02/2022, 8:40 AM
    Hey folks, is it possible to make a custom (de-) serializer (
    KSerializer
    ) configurable? Specifically I'm looking for a way to make a serializer for
    BigDecimal
    configurable regarding the scale of the
    BigDecimal
    . Contextual serialization doesn't seem to be a fit because it would only work per class and not per field, right?
    y
    4 replies · 2 participants
  • j

    jmfayard

    08/02/2022, 4:21 PM
    Bonjour, please tell me why my bad idea is indeed bad So I am doing lots of SQL and to decouple sql entities from domain classes, I have to write tons of dummy mappers from say
    UserProfileEntity
    (sql) to
    UserProfile
    who have the same properties And I'm bored to write those mappers manually In the .Net world, there is http://automapper.org/ for that I wonder I could just leverage
    kotlinx.serialization
    to transform
    UserProfileEntity
    to
    JsonElement
    and back to
    UserProfile
    j
    c
    +3
    11 replies · 6 participants
  • a

    Arnab

    08/03/2022, 11:36 AM
    Hi there! I am running into a Jackson issue with sealed classes. I have the following code:
    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
    sealed class Principal
    object AnonymousUser : Principal() {
      val _empty: String? = null
    }
    
    // other implementations of Principal
    
    fun main() {
      // jacksonObjectMapper() is a function in jackson which creates an object mapper with the Kotlin module
      val input = jacksonObjectMapper().writeValueAsString(AnonymousUser)
      val principal = jacksonObjectMapper().readValue(input, Principal::class.java)
      println(principal)
    }
    This gives me the following error:
    Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "_empty" (class com.example.hellojavabin.graphql.context.Principal$AnonymousUser), not marked as ignorable (0 known properties: ])
     at [Source: (String)"{"@type":"Principal$AnonymousUser","_empty":null}"; line: 1, column: 49] (through reference chain: com.example.hellojavabin.graphql.context.Principal$AnonymousUser["_empty"])
    What am I missing here? I also tried casting the input string directly to
    AnonymousUser
    but that fails with the same issue. Has anyone done something similar?
    1 reply · 1 participant
  • t

    Tower Guidev2

    08/03/2022, 1:48 PM
    Hi is there a "default" serializer for
    kotlin.Throwable
    ? and while i am here (Asking fro help) how do i resolved this duplicate name issue ?
    3 replies · 1 participant
  • a

    andylamax

    08/03/2022, 2:32 PM
    Why isn't Nothing Serializable by default? did the serialization team miss a use case for it? or where there ambiguations that led to it being stalled??
    v
    e
    3 replies · 3 participants
  • a

    Ayfri

    08/03/2022, 5:05 PM
    Is there a way to create a
    JSONTransformingSerializer
    to replace all keys with a
    snake_case
    instead of a
    camelCase
    that works for any data class ?
    d
    5 replies · 2 participants
  • d

    Dominaezzz

    08/04/2022, 9:13 AM
    Does the array always look like that?
    z
    1 reply · 2 participants
  • p

    Paul Woitaschek

    08/05/2022, 8:28 AM
    What is the benefit of using the
    Serializer
    annotation?
    h
    19 replies · 2 participants
  • j

    Joaco

    08/07/2022, 3:13 PM
    I just discovered the kotlinx.serialization library and it seems to work very well and I can use it as a substitute for jackson, I wanted to do a little performance test and if I use it as the documentation says
    val foo = Json.decodeFromString<Project>(string)
    I see that the performance drops much more than others like jackson and GSON. instead, if I instantiate the serializer and then reuse it, the performance works much better,
    val serializer = serializer(typeOf<Project>()) as KSerializer<Project>
    val foo = Json.decodeFromString(serializer, string)
    Is there a problem with doing it this way? more details in https://github.com/jcaromiq/serde-benchmark
    h
    e
    2 replies · 3 participants
  • b

    bbaldino

    08/11/2022, 5:08 PM
    I have a class structure roughly like:
    sealed class MessagePayload ...
    
    data class PayloadOne(val foo: String) : MessagePayload ...
    
    class Message(val msgType: MessageType, val payload: MessagePayload) { ... }
    and I was hoping to get it to serialize as:
    {
      "msgType": "payloadOne",
      "payload": {
        "foo": "..."
      }
    }
    that is: have the discriminant for the 'payload' field actually be at a layer "above", is that possible via just annotations? or would it require custom serializer/deserializer?
    d
    16 replies · 2 participants
  • z

    zt

    08/11/2022, 10:00 PM
    In
    JsonContentPolymorphicSerializer
    can I skip serializing an element? So if I dont have any serializers I can just skip it and it wont be included in the list
  • a

    akowal

    08/15/2022, 12:23 PM
    I have a class
    data class(val foo: String, ...)
    and in one context I need field
    foo
    to be serialized as
    bar
    (don’t need deserialization), but in other cases it should be de-/serialized as usual. How is it possible to achieve this?
    p
    3 replies · 2 participants
  • l

    Lukasz Kalnik

    08/16/2022, 11:10 AM
    Ah ok, I see, this is not a member function but an extension function and has to be manually imported:
    import kotlinx.serialization.decodeFromString
    l
    12 replies · 2 participants
  • a

    Angelo Rüggeberg

    08/17/2022, 9:50 PM
    hey, I feel super stupid as I fail to formulate a proper search 😄 I need to define a type that takes a generic. The issue is that I do get the target Type as argument (I am creating a retrofit converter but its not a retrofit specific question, just to mention some context). This is my generic class I want to serialize:
    data class Envelope<T> (
       val response: T
    )
    this is the method where i need to instance the generic typed method:
    override fun responseBodyConverter(
                type: Type,
                annotations: Array<Annotation>,
                retrofit: Retrofit
            ): Converter<ResponseBody, *>? {
    I cannot find any way to create a parameterized Class with type as
    Type
    parameter. I'd need something like this:
    val response : Envelope<type> = json.decodeFromString(...)
  • a

    Angelo Rüggeberg

    08/17/2022, 9:52 PM
    I keep finding solutions how to do it with moshi using:
    val typed = Types.newParameterizedType(Envelope::class.java, type)
    however I'd like to avoid pulling moshi in just to be able to work around the reflection definition
    n
    e
    7 replies · 3 participants
  • d

    dawidhyzy

    08/19/2022, 9:34 AM
    Is there a way to force serialization to use
    ksp
    instead of
    kapt
    ? I have a module that usess
    ksp
    only and fails after adding
    kapt
    j
    11 replies · 2 participants
  • c

    Christian Lutnik

    08/23/2022, 6:27 AM
    Hello! Is there a way to serialize properties of a (sealed) superclass without using surrogates?
    x
    2 replies · 2 participants
  • b

    benkuly

    08/25/2022, 7:54 AM
    After a large refactoring I get the following exception when running
    compileKotlinJs
    task. Any idea how to get more insights?
    --debug
    does not give more information.
    3 replies · 1 participant
  • r

    Rohde Fischer

    08/26/2022, 10:14 AM
    so, if I have a class that I want to serialize with a custom serializer, but don't want to add it in the annotation, and I'm using Spring Boot, so I don't call the framework directly, how can I register my serializer for use in my case?
  • j

    Jan Skrasek

    08/26/2022, 8:01 PM
    Hello, I have a custom format and Encoder/Decoder, however, it is just for top-level properties, the more complex (nested) inner values would be converted to json. Is there a way to delegate to
    JsonEncoder
    ? I think I should return
    JsonEncoder
    instance (
    JsonTreeEncoder
    ?) in my
    beginStructure
    method, but everything related to Json encoding seems to be internal. Is there a way? Thank you.
    1 reply · 1 participant
  • g

    Gabriel Quéré

    08/27/2022, 8:12 AM
    Hi, is there a kind of Gson's type adapter in kotlin serialization ?
    j
    1 reply · 2 participants
Powered by Linen
Title
g

Gabriel Quéré

08/27/2022, 8:12 AM
Hi, is there a kind of Gson's type adapter in kotlin serialization ?
j

jw

08/27/2022, 1:11 PM
KSerializer is basically that, yes
View count: 15