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

    Daniele Andreoli

    06/13/2022, 8:54 AM
    good morning, I’m sorry if this is a recurring or a trivial question but it’s my first time I had to write custom serializer/deserializer for a project and i’m a little confused. I have to migrate an old GSON Deserializer for a data class that look like this:
    @Serializable(with = PaymentInfoSerializer::class)
    data class PaymentInfo(
    val id: PaymentId,
    val amount: Float,
    val paidAt: String?,
    val productId: ProductId
    )
    The last field is a typealias for a Int type but it’s actually an evaluated one. The field is a field taken from an inner Json Object like this:
    "product":{"id":74}
    so the value is just the id field. The entire json is like this one:
    "id":22,"paidAt":null,"amount":720.0,"description":null,"product":{"id":74}
    So my problem is that I can’t use simple deserilization with dataclass because I have to keep the code working but i can’t figure out how a map object is actually descripted inside a desirializer. I’have written a descriptor like this but i’m not sure how ti could work as I have no way to tell it to take just the id field inside the map:
    override val descriptor: SerialDescriptor =
    buildClassSerialDescriptor("PaymentInfo") {
    element<PaymentId>("id")
    element<Float>("amount")
    element<String?>("paidAt", isOptional = true)
    element<Map<String, Int>>("product")
    }
    At the end, i’ve to find a way to tell serilization to do something like this in GSON:
    productId = jsonObject.get("product").asJsonObject.get("id").asInt
    I've read the doc but I can't find some example that actually seems to fit and since I have to migrate a lot of this custom serializer I'm tring to start with the correct structure. Is there someone who could help? Thanks
    r
    • 2
    • 5
  • l

    Landry Norris

    06/13/2022, 6:05 PM
    [Resolved] I’ve started seeing this error on iOS recently
    * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x8)
    `frame #0: 0x000000010d014d10 MyFramework`kfun:kotlinx.serialization.json.Json#encodeToString(kotlinx.serialization.SerializationStrategy<0:0&gt;;0:0){0§<kotlin.Any?>}kotlin.String [inlined] Composer at Composers.kt:13:9` I’m using a standard
    json.encodeToString(Model.serializer(), model)
    using
    private val json = Json {
        isLenient = true
        ignoreUnknownKeys = true
    }
    Everything works fine on Android, but fails on iOS. What should I be looking for?
    • 1
    • 1
  • c

    Chris Fillmore

    06/14/2022, 4:52 PM
    Hi folks, I’m trying to find my way around R8 / ProGuard config. I’m just using a dummy test project with
    minifyEnabled true
    on the release build. My question is, is it necessary to configure ProGuard for Kotlin serialization, if you always provide a serializer explicitly? So I mean, in every case I call it like this:
    serializer.decodeFromString(MyData.serializer(), json)
    // or
    serializer.encodeToString(MyData.serializer(), myObj)
    On observation, my program seems to work fine with obfuscation enabled, without any ProGuard configuration, if I am passing the serializer like this. This seems to contradict the docs:
    The library works on Android, but, if you’re using ProGuard, you need to add rules to your
    <http://proguard-rules.pro|proguard-rules.pro>
    configuration to cover all classes that are serialized at runtime.
    e
    • 2
    • 3
  • a

    Andrey Tabakov

    06/15/2022, 11:51 AM
    Why variable that starts with
    is
    is omitted while serialization? I have data class
    @Serializable
    public data class Config(
        val isVariable: String,
        val anotherVariable: String
    )
    
    Config("omit", "value")
    Output will be:
    {anotherVariable:"value"}
    P.S. isVariable should be boolean, I know, anyway it should be a String in my case
    e
    • 2
    • 3
  • e

    ermac10k

    06/21/2022, 10:30 AM
    Hello! Are there any plans to fix this: https://github.com/Kotlin/kotlinx.serialization/issues/1051 It’s a real pain in the neck. Unfortunately, it is the reason to reject using kotlin.serialization in systems with money involved
    👍 2
    e
    • 2
    • 2
  • r

    ribesg

    06/24/2022, 4:04 PM
    Is there a better way to get the serializer for a generic type if it’s not reified but you have its class?
    class Generic<T : Any>(
        private val clazz: KClass<out T>,
    ) {
    
        init {
            require(clazz.hasAnnotation<Serializable>())
        }
    
        fun serialize(value: T): String {
            val type = clazz.createType()
            val serializer = Json.serializersModule.serializer(type)
            return Json.encodeToString(serializer, value)
        }
    
    }
    e
    • 2
    • 1
  • j

    jessewilson

    06/25/2022, 1:00 AM
    How experimental is
    SerializersModule.getContextual(...)
    ? I’ve got a library that uses this behavior. I’m fine to ship a new release if this function’s signature changes, but I’m in deep trouble if the feature goes away altogether!
  • j

    jessewilson

    06/25/2022, 1:06 AM
    ALSO! I’m looking forward to stable APIs for
    Json.decodeFromDynamic
    +
    Json.encodeToDynamic
    . On the JS engine I’m using (QuickJS) using these APIs has a massive performance advantage over doing encoding with Kotlin/JS and StringBuilder. (QuickJS doesn’t use ropes internally in its strings, so
    StringBuilder
    is sloooow!) Any ETA on stability here? Would y’all accept a pull request to remove
    @ExperimentalSerializationApi
    on these?
  • r

    ribesg

    06/29/2022, 11:22 AM
    What is this?
    java.lang.VerifyError: class kotlinx.serialization.json.internal.StreamingJsonDecoder overrides final method kotlinx.serialization.encoding.AbstractDecoder.decodeSerializableElement(Lkotlinx/serialization/descriptors/SerialDescriptor;ILkotlinx/serialization/DeserializationStrategy;Ljava/lang/Object;)Ljava/lang/Object;
    p
    • 2
    • 7
  • s

    snowe

    06/29/2022, 11:16 PM
    I have an arrow Either deserializer that I found in a thread here, that I’ve slightly modified, but for some reason it fails if my object has a different class discriminator, even if I specify a specific one just for the deserializer. no clue what’s going on. anyone?
    class EitherSerializer<R>(
        private val leftSerializer: KSerializer<PricingError>,
        private val rightSerializer: KSerializer<R>,
    ) : KSerializer<Either<PricingError, R>> {
        override val descriptor: SerialDescriptor
            get() = rightSerializer.descriptor
    
        private val errorJson = Json {
            ignoreUnknownKeys = true
            isLenient = true
            encodeDefaults = true
        }
    
        override fun deserialize(decoder: Decoder): Either<PricingError, R> {
            require(decoder is JsonDecoder) { "only works in JSON format" }
            val element = Either.catch {
                decoder.decodeJsonElement()
            }.mapLeft { PricingError.SerializationError(it.localizedMessage) }
            return when (element) {
                is Either.Left -> element
                is Either.Right -> {
                    try {
                        decoder.json.decodeFromJsonElement(rightSerializer, element.value).right()
                    } catch (_: SerializationException) {
                        errorJson.decodeFromJsonElement(leftSerializer, element.value).left() // fails here with error in thread
                    }
                }
            }
        }
    
        override fun serialize(encoder: Encoder, value: Either<PricingError, R>) {
            TODO("Not yet implemented")
        }
    }
    d
    e
    • 3
    • 29
  • j

    jw

    06/30/2022, 2:15 PM
    i have a public interface with properties in module A, a private data class implementing the interface in module B, and in module C (the only one I control) i need to create a serializer for the interface type (for encoding only). Are my only options a manually-written serializer for the interface or a surrogate? i really would like to avoid having to maintain a hand-written serializer but also would like the serialize without extra allocation of surrogates for every instance in the outgoing tree. My dream would be external seriazation generation through
    @Serializer(forClass=)
    but for an interface where the generated decoder throws UOE, or I could manually override decode and throw UOE
    d
    • 2
    • 4
  • r

    Rahim Klaber

    07/03/2022, 1:32 PM
    Hi I'm trying to deserialize json to a sealed class, but it fails with a decoding exception that says
    Exception in thread "main" kotlinx.serialization.json.internal.JsonDecodingException: Expected JsonPrimitive at self, found {"href":"<https://horizon.stellar.org/operations/122511124621283329>"}
    . Could anyone take a look and tell me if I'm missing something obvious?. I'll put the code in the replies.
    a
    • 2
    • 14
  • r

    ritesh

    07/03/2022, 6:27 PM
    👋 A question on proto-buff data-store in android. I realised tool like flipper doesn’t support proto-buff yet. I was writing a flipper plugin for it and the approach i took was - from client/consumer end i am converting the protobuff to json and then sending it to the flipper Android plugin, which reads it and send it’s to the desktop flipper plugin. Was wondering if there is a better approach in proto-buff world, where i can avoid converting it to json and sending it as string, as any client/server needs the
    proto
    schema for serialising or deserialising it.
    :plus1: 1
    • 1
    • 2
  • y

    Yao-Wen Mei

    07/06/2022, 9:40 PM
    Hello, a question on use
    @SerialInfo
    annotation on Java annotations: we have a Kotlin library which is depend on our Java library and use some of the Java annotations. I want to use some of the Java annotations during Kotlin serialization process. In order to do this, I have to 1) add
    @SerialInfo
    on the Java annotations, and 2) define an inner class
    Impl
    inside of my Java annotation for the Kotlin complier plugin. The working code is like below:
    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.FIELD, ElementType.METHOD})
    @SerialInfo  //<--------------------------------------------------------- Add this line
    @kotlin.annotation.Target(allowedTargets = AnnotationTarget.PROPERTY)
    public @interface ServerTimestamp {
    
      final class Impl implements ServerTimestamp { // <--------------------- Add this block
        @Override
        public Class<? extends Annotation> annotationType() {
          return (Class<? extends Annotation>) ServerTimestamp.class;
        }
      }
    }
    My question is will the complier plugin always looking for the
    Impl
    inner class in the future? How stable this mechanism is going to be? Thank you~
    e
    • 2
    • 1
  • y

    Yao-Wen Mei

    07/06/2022, 9:57 PM
    Another conjugate question: What is the process if I want to apply
    @Serializable (with = customJavaSerializer.class)
    annotation on a Java class? (I want to have both the class itself and the custom serializer defined in Java, but use them in Kotlin) I have tried define a Java class
    Hello
    , and then define a custom serializer
    HelloSerializer
    in Java. What is the field name or method name (like the
    Impl
    in the previous annotation example) should I give, so that the complier plugin can get access to my custom java serializer with
    @Serializable
    ? Thank you very much.
    e
    • 2
    • 15
  • m

    Martin Gaens

    07/06/2022, 11:15 PM
    Hello! How would I create a
    JsonContentPolymorphicSerializer
    for the following class hierarchy? I want it to select the proper serializer by checking the value of the "ok" key in the JSON and if it's true, return a
    ApiResponse.Success
    serializer and if false return the
    ApiResponse.Error
    serializer.
    @Serializable
    internal sealed class ApiResponse {
    
        @SerialName("ok") abstract val ok: Boolean
    
        @Serializable
        class Success<T>(
            override val ok: Boolean,
            @SerialName("result") val result: T
        ) : ApiResponse()
    
        @Serializable
        class Error(
            override val ok: Boolean,
            @SerialName("error_code") val errorCode: Int,
            @SerialName("description") val description: String
        ) : ApiResponse()
    }
    e
    • 2
    • 10
  • m

    Martin Gaens

    07/08/2022, 10:44 PM
    Is there any builtin datetime serialization? Or do I have to make a serializer myself?
    e
    • 2
    • 4
  • m

    Martin Gaens

    07/09/2022, 12:19 AM
    What would be the recommended way to serialize/deserialize money amounts? I'm getting a decimal amount of money from an API and
    BigDecimal
    doesn't have a default serializer. Is the best thing to do creating a serializer for
    BigDecimal
    ?
    e
    • 2
    • 5
  • a

    Adam S

    07/11/2022, 9:55 AM
    I'm parsing some JSON API responses returns an empty object
    {}
    if a list is empty I've written a custom serializer to handle this, and set
    contextual(List::class)
    in the
    SerializersModule
    , but I forgetting to add
    @Contextual
    to all the list properties. Is there a way to hardcode 'use my
    EmptyListEmptyObjectSerializer
    for all `List<>`s' in a
    SerializersModule
    ?
    main.kt
    • 1
    • 2
  • s

    Stylianos Gakis

    07/12/2022, 1:01 PM
    I got an interface
    Action
    with normal subclass
    class SomeAction : Action
    and another interface subclass of type
    interface ServerAction : Action
    which itself has implementations like
    class SpecificServerAction : ServerAction
    . I’ve been trying to think of how I need to setup my SerializersModule to make all of this work. From what I understand since my interface is not sealed, I need to do something like this
    polymorphic(Action::class) {
        subclass(ServerAction::class, //??)
        subclass(NavigationPushAction::class, NavigationPushAction.serializer())
        subclass(NavigationPopAction::class, NavigationPopAction.serializer())
        subclass(VoidAction::class, VoidAction.serializer())
    }
    but how do I do this for the ServerAction? Optimally I’d like to be able to define my ServerAction hierarchy the same way by providing all the subclasses, but I don’t see a way that the dsl allows me to do this? I could probably do this by creating my own
    object ServerActionSerializer : KSerializer<ServerAction> {
    and implementing it, but I’d rather not if possible? I like this subclass approach which can take care of it for me. Am I missing something, any ideas maybe? Some part of the api I can be using that I am not?
    e
    e
    • 3
    • 6
  • y

    Yao-Wen Mei

    07/12/2022, 7:30 PM
    Hello, I have a Java library and a Koltin library is depending on the Java library. In the java library I have a class,
    Foo.java
    , Is that possible I can to mark it
    @Serializable (with = ContextualSerializer<Foo>.class)
    in side of Java, then use this
    Foo.java
    in my Kotlin library as it is
    Serializable
    , where inside of the Kotlin library, I define the
    SerializerModule
    (build a contextual serializer for Foo.java class and also a list of other classes), and then pass the
    SerializerModule
    to my custom ktxEncoder/ktxDecoder; The key point for me to doing this is to avoid define a Kotlin serializer for
    Foo.java
    in my Java library (we are trying to have at least Kotlin file in the Java lib as possible). Also trying to avoid the
    @Contextual
    annotation for my customers;
    👎 1
    b
    p
    • 3
    • 3
  • d

    darkmoon_uk

    07/16/2022, 12:18 AM
    Is there a way to configure JSON serialization that, when deserializing, it should populate any encountered but unknown keys into some 'extras'
    Map<String, JsonElement>
    in the object? I've seen this feature exist in other frameworks e.g. Jackson. It can be used to afford a certain degree of future proofing to information-oriented API's e.g. the data could still be presented to the user and re-serialized as original.
    e
    • 2
    • 3
  • b

    Ben Woodworth

    07/16/2022, 3:11 PM
    So I'm implementing a format for kxs (knbt). Is there a recommended way to run tests on a format? My first thought is that it would be cool if there were some kind of "test-suite-for-3rd-party-kxs-formats" dependency I could pull in, maybe abstract test suites for
    BinaryFormat
    and
    StringFormat
    that could be extended, overriding some format-specific details (like instantiation?) Otherwise I'm thinking of using the json tests as a starting point. I think my format is already well tested, I'm just worried I've got some small oversights. I'm also looking to implement support for polymorphism which I'm less comfortable with so knowing I've got all my bases covered would be reassuring :)
  • v

    vqrs

    07/19/2022, 8:08 PM
    What guidelines do you use for schema evolution to have forward and backward compatibility? How do you test it? I can't find anything in the docs about how older code might read a newer format and what guarantees I get
    👍 1
    • 1
    • 1
  • i

    Igor Kolomiets

    07/20/2022, 2:58 PM
    kotlinx-serialization 1.4.0-RC makes unsigned types a stable feature, so explicit opt-in is no longer required: https://github.com/Kotlin/kotlinx.serialization/pull/1962 But why the core interfaces such as Encoder/Decoder still don’t have specific
    encodeU...
    /
    decodeU...
    methods for unsigned types, so generic
    encodeSerializable…
    /
    decodeSerializable…
    methods that require explicit serializer for the value have to be used when dealing with unsigned values?
    e
    • 2
    • 2
  • r

    ribesg

    07/20/2022, 3:24 PM
    Using Kotlin 1.7.10, kotlinx.serialization 1.3.3 I'm stuck on this error, I don't know what it means. I don't know what it's looking for exactly.
    > Task :linkPodDebugFrameworkIosArm64 FAILED
    e: Could not find "org.jetbrains.kotlinx:kotlinx-serialization-core" in [/Users/ribesg/Projects/events, /Users/ribesg/.konan/klib, /Users/ribesg/.konan/kotlin-native-prebuilt-macos-aarch64-1.7.10/klib/common, /Users/ribesg/.konan/kotlin-native-prebuilt-macos-aarch64-1.7.10/klib/platform/ios_arm64]
    If I try with kotlinx.serialization 1.4.0-RC I get this:
    > Task :linkPodDebugFrameworkIosArm64 FAILED
    e: Compilation failed: Expecting descriptor for kotlinx.serialization/MissingFieldException.<init>|399804788095754142[0]
    
     * Source files:
     * Compiler version info: Konan: 1.7.10 / Kotlin: 1.7.20
     * Output kind: STATIC_CACHE
    
    e: java.lang.IllegalStateException: Expecting descriptor for kotlinx.serialization/MissingFieldException.<init>|399804788095754142[0]
            at org.jetbrains.kotlin.backend.konan.serialization.KonanIrLinker$KonanCachedLibraryModuleDeserializer.deserializeIrSymbol(KonanIrlinker.kt:635)
            at org.jetbrains.kotlin.backend.common.serialization.FileDeserializationState$symbolDeserializer$3.invoke(IrFileDeserializer.kt:88)
            at org.jetbrains.kotlin.backend.common.serialization.FileDeserializationState$symbolDeserializer$3.invoke(IrFileDeserializer.kt:77)
            at org.jetbrains.kotlin.backend.common.serialization.IrSymbolDeserializer.deserializeIrSymbolData(IrSymbolDeserializer.kt:67)
    ✅ 1
    • 1
    • 4
  • p

    Partho Paul

    07/21/2022, 5:51 AM
    Hi, I’ve a use case wherein I want to parse two different attributes from a json into a single variable. It is guaranteed that I’ll be getting only one of such attribute at a time. For example my json will either be:
    {"id1" : "1", "name" : "xyz"}
    or
    {"id2" : "1", "name" : "xyz"}
    and my DTO is
    data class MyObj(val id: String, val name: String)
    . Is it possible to address such a use case using kotlinx serialization?
    h
    • 2
    • 1
  • r

    Robert Jaros

    07/21/2022, 8:23 AM
    https://github.com/Kotlin/kotlinx.serialization/releases/tag/v1.4.0-RC
    :kotlin-intensifies-purple: 6
  • v

    Vivek Modi

    07/21/2022, 9:35 AM
    Hey guys, what the meaning of this error
    kotlinx.serialization compiler plugin is not applied to the module, so this annotation would not be processed. Make sure that you've setup your buildscript correctly and re-import project.
    m
    j
    • 3
    • 9
  • v

    Vivek Modi

    07/21/2022, 11:05 AM
    Another question, can we serialization in desired format ?
    {
        "TopicOne": [
            {
                "id": 1,
                "seconds": 5.856,
                "date": "21/10/2010"
            },
            .... // more data 
        ],
        "TopicTwo": [
            {
                "gameNumber": 6,
                "name": "Heat",
                "date": "21/11/2010"
            },
            ..... // more data
        ],
        "TopicThree": [
            {
                "id": 1,
                "numberOfSets": 3,
                "date": "21/11/2011",
       
            }, 
            ....// more data
        ]
    }
    and see more in thread..
    • 1
    • 6
Powered by Linen
Title
v

Vivek Modi

07/21/2022, 11:05 AM
Another question, can we serialization in desired format ?
{
    "TopicOne": [
        {
            "id": 1,
            "seconds": 5.856,
            "date": "21/10/2010"
        },
        .... // more data 
    ],
    "TopicTwo": [
        {
            "gameNumber": 6,
            "name": "Heat",
            "date": "21/11/2010"
        },
        ..... // more data
    ],
    "TopicThree": [
        {
            "id": 1,
            "numberOfSets": 3,
            "date": "21/11/2011",
   
        }, 
        ....// more data
    ]
}
and see more in thread..
I have created data class for this
data class TopicResponse(
    val topicOne: List<TopicOne>? = null,
    val topicTwo: List<TopicTwo>? = null,
    val topicThree: List<TopicThree>? = null
)

data class TopicOne(val id: Int? = null, val seconds: String? = null, val date: String? = null)
data class TopicTwo(val gameNumber: Int? = null, val name: String? = null, val date: String? = null)
data class TopicThree(val id: Int? = null, val numberOfSets: String? = null, val date: String? = null)
So
date
is common so created a base class
@Serializable
abstract class TopicBase {
    abstract val date: String
}
inherit this to child class
@Serializable
class ChildTopicOne(override val date: String, private val id: Int, private val seconds: String?) : TopicBase() {
   fun getString() :String {
       return "Id $id has to complete the race in $seconds seconds"
   }
}

@Serializable
class ChildTopicTwo(override val date: String, val gameNumber: Int, val name: String?) : TopicBase() {
    fun getString() :String {
        return "gameNumber $gameNumber has to complete the race in $name name"
    }
}

@Serializable
class ChildTopicThree(override val date: String, val id: Int, val numberOfSets: String?) : TopicBase() {
    fun getString() :String {
        return "id $id has to complete the race in $numberOfSets numberOfSets"
    }
}
I tried some code but it not giving me correct output, what I want
response.topicOne?.forEach { topicOne ->
     topicOne.date?.let {
          val value: TopicBase = ChildTopicOne(it, topicOne.id, topicOne.seconds)
          val data = Json.encodeToJsonElement(value)
          Log.e("data", "${data}")
     }
}
Actual Output
{
  "type": "com.vivek.example.data.ChildTopicOne",
  "date": "21/10/2010",
  "seconds": "5.856",
  "id": "1"
}
Expected Output
{
  "type": "com.vivek.example.data.ChildTopicOne",
  "getString": "Id 1 has to complete the race in 5.856 seconds"
}
Is it possible to get this type of output?
@Javier @mbonnin do you any idea about this?
View count: 3