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

    ankushg

    08/31/2021, 11:36 PM
    Hey friends! Looking for some help on keeping a subset of JSON in string-form I have JSON like
    {
      "id": "file",
      "value": "File",
      "popup": {
        "menuitem": [
          {
            "value": "New",
            "onclick": "CreateDoc()"
          },
          {
            "value": "Open",
            "onclick": "OpenDoc()"
          },
          {
            "value": "Save",
            "onclick": "SaveDoc()"
          }
        ]
      }
    }
    I'd like to represent it with a
    data class Menu(val id: String, val value: String, val popup: String)
    where the
    popup
    subtree is stored as a String of valid JSON, instead of having to deserialize the whole nested
    popup
    structure. Happy to write a custom serializer for this because it doesn't happen too frequently in our codebase.
    e
    • 2
    • 7
  • p

    Pitel

    09/01/2021, 11:42 AM
    Hi, how can I configure kotlinx JSON serializer to not quote the key? Like this:
    {noQuote: "foobar"}
    p
    • 2
    • 1
  • n

    nilTheDev

    09/03/2021, 7:56 AM
    Just a while ago it was working like a charm. Not sure why it's not working right now. Any idea?
    j
    • 2
    • 1
  • e

    Eric Ampire [MOD]

    09/03/2021, 2:17 PM
    Hello everyone, I have a class hierarchy like the following, and I have an API that return a list of
    User
    I can retrieved Users using two different end-points, The first one return
    recent
    users and the second one return
    popular
    users, for both popular and recent end-points the data returning by the API has the same structure except one thing The recent end-point return a json like this, that differ from the popular end-point at the recent field
    {
      "data": {
        "recent": { ... } // Here the difference
       }
    }
    And the popular end-point return a json like this, that differ from the recent end-point at the popular field
    {
      "data": {
        "popular": { ... } // Here the different 
       }
    }
    Here the class hierarchy
    @Serializable
    data class ApiResponse(
      @SerialName("data")
      val apiData: Data
    )
    
    @Serializable
    data class Data(
      @SerialName("recent") // My problem is here
      val page: Page
    )
    
    @Serializable
    data class Page(
      val currentPage: Int,
      val from: Int,
      val perPage: Int,
      val results: List<User>,
    )
    For the
    Data
    class, there is a way to customize the behavior of the
    SerialName
    annotation to deal both with recent and popular name as the
    Page
    class has the same structure for recent and popular end-point without having to duplicate stuff ??
    m
    j
    r
    • 4
    • 7
  • e

    Eric Ampire [MOD]

    09/04/2021, 3:23 AM
    Hi all, I get this error
    Can't use arguments with defaults for serializable annotations yet
    every time I use
    @JsonNames
    annotation Kotlin=1.5.21 Ktor=1.6.3 I'm not using the latest version of Kotlin because my project uses Jetpack Compose
    The root cause java.lang.IllegalArgumentException was thrown at: org.jetbrains.kotlinx.serialization.compiler.backend.jvm.SerializerCodegenImpl.addSyntheticAnnotationsToDescriptor(SerializerCodegenImpl.kt:123)
    t
    • 2
    • 1
  • s

    sandwwraith

    09/06/2021, 3:47 PM
    📣 kotlinx.serialization
    1.3.0-RC
    has been released! It contains a lot of interesting features and improvements, such as: • Integration with Java streams; • Property-level control over defaults values encoding; • Per-hierarchy polymorphic class discriminators; • Excluding null values from JSON serialization. You're welcome to evaluate it and share your feedback. Full release notes here: https://github.com/Kotlin/kotlinx.serialization/releases/tag/v1.3.0-RC
    🎉 14
    n
    d
    • 3
    • 3
  • a

    Ayfri

    09/06/2021, 8:14 PM
    Hi, I'm using serialization 1.5.30 and I'm having a weird issue when I try to parse a JSON :
    Exception in thread "main" kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 0: Expected end of the object '}', but had '{' instead
    JSON input: {"keywords":[],"softKeywords":[],"modifierKeywords":[],"specialIdentifiers":[],"operators":[]}
    	at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:24)
    	at kotlinx.serialization.json.internal.JsonExceptionsKt.JsonDecodingException(JsonExceptions.kt:32)
    	at kotlinx.serialization.json.internal.JsonLexer.fail(JsonLexer.kt:493)
    	at kotlinx.serialization.json.internal.JsonLexer.fail(JsonLexer.kt:215)
    s
    • 2
    • 3
  • s

    sushma nayak

    09/08/2021, 12:32 PM
    Hi.. I wanted to know how to serialize a json generic property whose type is known only at runtime. Eg:
    "response":{
    "value":5
    }"
    Value can be Int or string or a list of some other type.
    s
    • 2
    • 2
  • j

    Justin Tullgren

    09/09/2021, 5:31 PM
    Is java's
    serialVersionUID
    completely unnecessary when saving to disk using serialization and then deserializing to a potentially modified class type later?
    b
    e
    • 3
    • 7
  • e

    Emil Kantis

    09/09/2021, 7:34 PM
    I have some nested generic sealed hierarchies using
    @Serializable
    and getting the following (in thread) exception from compiler when building.. Is this a known issue? Is there something one must avoid to prevent this? Edit: Upgrading 1.2.1 -> 1.2.2 fixed it!
    • 1
    • 1
  • d

    Danish Ansari

    09/12/2021, 9:43 AM
    Trying to serialize generic data class having with default value produces empty JSON object
    {}
    Easiest way to reproduce this issue is to try official generic classes example, add
    data
    modifier to the class and have default value (eg. in thread) https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/basic-serialization.md#generic-classes I'm using kotlinx.serialization v1.2.2 and Kotlin v1.5.21 Update: All I had to do was read this section of doc 😅https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/json.md#encoding-defaults
    e
    • 2
    • 2
  • e

    Emil Kantis

    09/13/2021, 2:55 PM
    Very frustrating.. Small tweak in data classes and all of a sudden kotlinx.serialization causes compiler errors like this. Is there any known pitfalls to avoid getting problems like this?
    org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't transform method node:
    write$Self (Ldev/kantis/Square;Lkotlinx/serialization/encoding/CompositeEncoder;Lkotlinx/serialization/descriptors/SerialDescriptor;Lkotlinx/serialization/KSerializer;Lkotlinx/serialization/KSerializer;)V:
      @Lkotlin/jvm/JvmStatic;()
        // annotable parameter count: 5 (visible)
        // annotable parameter count: 5 (invisible)
        @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
        @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 1
        @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 2
        @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 3
        @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 4
    
    [Full error in thread]
    • 1
    • 2
  • c

    Chachako

    09/14/2021, 3:57 PM
    What did I do wrong? Why
    stars
    is not encoded to json❓
    e
    d
    • 3
    • 4
  • c

    Chachako

    09/16/2021, 4:09 AM
    Does kotlinx-serialization allow serialization/deserialization to html? or is there any useful library to do this?
    t
    • 2
    • 5
  • s

    Sergey Akhapkin

    09/17/2021, 1:33 PM
    Hi everybody. May be someone is familiar with changes around Kotlin's 'object' (and may be sealed classes) made between 1.3.50 and 1.4.30 ? I missed that and cannot find in changelog anything related. Following code works quite different on these versions:
    @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
    sealed class A {
        @JsonTypeName("B")
        object B: A()
        @JsonTypeName("C")
        object C: A()
        @JsonTypeName("D")
        data class D(val i: Int): A()
    }
    
    class JsonTest {
        private val objectMapper = jacksonObjectMapper().apply(configureObjectMapper)
        private fun <T> parse(str: String, clazz: Class<T>): T = objectMapper.readValue(str, clazz)
        private fun <T> stringify(value: T): String = objectMapper.writeValueAsString(value)
    
        @Test
        fun testPatternMatching() {
            val x1 = A.B
            val x2 = parse(stringify(x1), A::class.java)
            val x3 = A.C
    
            listOf(x1,x2,x3).forEach {
                when(it) {
                    A.B -> println("b ${it as Any}")
                    A.C -> println("c ${it as Any}")
                    is A.D -> println("d ${it as Any}")
                    else -> println("? ${it as Any}")
                }
            }
            assertEquals(A.B, x1)
            assertEquals(A.B, x2) // <--- failed assertion in 1.4.30
            assertEquals(x1, x2)
        }
    }
    In 1.3.50 projects, it prints:
    b com.example.A$B@184a254d
    b com.example.A$B@184a254d
    c com.example.A$C@41443428
    In 1.4.30 (and 1.5.x) projects, it prints:
    b com.example.A$B@12a1cc8d
      ? com.example.A$B@7b2edf94
      c com.example.A$C@73baae4e
    and test fails with
    expected:<com.example.A$B@12a1cc8d> but was:<com.example.A$B@7b2edf94>
    As I can see - after serialization/deserialation I got 2nd A.B object (nonsense for a singleton). This code can be fixed by writting 'is A.B', in that case both instances (x1 and x2) will be matched. But who knows what is going on here and why it changed since 1.4.x ?
    e
    e
    • 3
    • 15
  • n

    Narek Mailian

    09/21/2021, 4:58 PM
    umm so I have this thing
    @Serializable
    data class ProjectIdWrapper(
    	val id: ProjectId,
    	val item: Project)
    @Serializable
    data class Project(
    	val projectProperty1: String,
    	val projectProperty2: String
    )
    but I want to have ProjectIdWrapper serialized/deserialized as
    {
      "id": 12121,
      "projectProperty1": "AAA",
      "projectProperty2": "BBB"
    }
    Is this possible? Or even better, can the IdWrapper be made generic? 😊
    s
    e
    • 3
    • 4
  • m

    Moritz Post

    09/22/2021, 2:30 PM
    Hello. I am trying to deserialize a json array of "unstructured" operation descriptions into an object. The format is similar to
    ["create", true, {more: "properties"]
    . There are more types than just the
    "create"
    shown here. I have attempted many different approaches but none were successful so far. What would be the best approach for such an input?
    p
    • 2
    • 2
  • j

    Jan

    09/22/2021, 2:31 PM
    I'm not sure what this error is trying to tell me. (Its trying to serialize "type")
    Exception in thread "DefaultDispatcher-worker-10" kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 14: Expected beginning of the string, but got ,
    JSON input: {"type":"rich","author":{"name":"author"}}
    e
    • 2
    • 2
  • m

    Moritz Post

    09/23/2021, 10:24 AM
    Ok, i made some progress by using
    override val descriptor: SerialDescriptor = buildSerialDescriptor("Create", StructureKind.LIST) {
          element("target", serialDescriptor<String>())
          element("method", serialDescriptor<String>())
          element("properties", serialDescriptor<Map<String, Any>>())
        }
    The remaining problem now is the Map<String, Any> part where i want to resolve the properties into a Map with properties and possible sublists. However there is not serializer for
    Any
    . Any advice on how to serialize the Any correctly within the properties map?
    e
    • 2
    • 8
  • е

    Евгений Попович

    09/23/2021, 12:36 PM
    Hi all please tell me how can I represent this object as a given json? {'response': {'code':0, 'message':'msg'}}
    @Serializable
    data class ReportUserResponse(
        val message: String,
        val code: Int,
    )
    without having to create another class with a 'response' field ?
    n
    • 2
    • 2
  • d

    Daniele B

    09/24/2021, 1:24 AM
    I would like to serialize this class:
    @Serializable
    data class RpcRequest(
      @SerialName("jsonrpc") val jsonrpc : String,
      @SerialName("id") val id : Int,
      @SerialName("method") val method : String,
      @SerialName("params") val params : List<@Contextual Any>?,
    )
    where
    params
    could be a list of any kind of object I currently get this error:
    Serializer for class 'Any' is not found.
    Mark the class as @Serializable or provide the serializer explicitly.
    An example of RpcRequest object:
    val req = RpcRequest("2.0",2342,"getData",listOf("erwrwee",{"encoding":"base64"}))
    How can it be properly serialized?
    i
    r
    +2
    • 5
    • 13
  • m

    Moritz Post

    09/24/2021, 3:19 PM
    may i add a general comment? kotlinx serialization is hard. anything but a direct conversion requires tremendous work. if it weren't for KMP i would stick with gson or moshi. Hope other json serialization libraries become KMP capable soon.
    ➕ 1
    j
    b
    +3
    • 6
    • 76
  • n

    nordiauwu

    09/25/2021, 2:18 PM
    Where can I find the source code for this library's gradle and kotlin plugins?
    t
    • 2
    • 1
  • a

    altavir

    09/27/2021, 9:37 AM
    Is current serialization compatible with 1.6-M1? I am willing to try EAP, but from experience I know that the serialization is frequently broken on EAPS.
    s
    o
    • 3
    • 3
  • s

    sandwwraith

    09/27/2021, 10:43 AM
    📣 kotlinx.serialization
    1.3.0
    has been released! This release brings a lot of new features, such as preview of
    <http://java.io|java.io>.*Stream
    -based serialization, additional control over default and nullable properties, and more. Check out the blogpost and the changelog: https://blog.jetbrains.com/kotlin/2021/09/kotlinx-serialization-1-3-released/ https://github.com/Kotlin/kotlinx.serialization/blob/v1.3.0/CHANGELOG.md
    👏🏻 1
    🎉 7
    👏 6
    a
    • 2
    • 1
  • d

    Didier Villevalois

    09/27/2021, 3:41 PM
    Hi! I am trying to use
    JsonContentPolymorphicSerializer
    to manually select what de-serializer to use for my polymorphic class hierarchies, while using
    JsonTransformingSerializer
    to remove the
    type
    fields at serialization. I am doing this:
    inline fun <reified T : Any> noDiscriminatorPolymorphic(crossinline serializerSelector: (element: JsonElement) -> DeserializationStrategy<out T>): KSerializer<T> {
        val serializer = object : JsonContentPolymorphicSerializer<T>(T::class) {
            override fun selectDeserializer(element: JsonElement): DeserializationStrategy<out T> {
                return serializerSelector(element)
            }
        }
        return NoDiscriminantSerializer(serializer)
    }
    
    class NoDiscriminantSerializer<T : Any>(serializer: KSerializer<T>) :
        JsonTransformingSerializer<T>(serializer) {
        override fun transformSerialize(element: JsonElement): JsonElement {
            val content =
                element.jsonObject.mapValues { (_, v) -> if (v is JsonObject) JsonObject(v.jsonObject - "type") else v } - "type"
            return super.transformSerialize(JsonObject(content))
        }
    }
    and then this:
    val myFormat = Json {
        serializersModule = SerializersModule {
            contextual(noDiscriminatorPolymorphic { element ->
                when {
                    "thisField" in element.jsonObject -> ThisClass.serializer()
                    "thatField" in element.jsonObject -> ThatClass.serializer()
                    else -> error("Unknown subclass")
                }
            })
        }
    }
    But the
    type
    fields are always serialized. Does anyone know what I am missing?
    e
    • 2
    • 3
  • r

    rnentjes

    09/28/2021, 8:33 AM
    Hi, after updating to 1.3.0 and trying out 'explicitNulls = false' I get this:
    Exception in thread "main" java.lang.NoSuchMethodError: 'void kotlinx.serialization.json.JsonBuilder.setExplicitNulls(boolean)'
    at com.banktrade.sequoia.serialization.SerializationConfig$updateSerialFormat$1.invoke(SerializationConfig.kt:55)
    at com.banktrade.sequoia.serialization.SerializationConfig$updateSerialFormat$1.invoke(SerializationConfig.kt:47)
    at kotlinx.serialization.json.JsonKt.Json(Json.kt:137)
    at kotlinx.serialization.json.JsonKt.Json$default(Json.kt:135)
    Anyone else tried this one out already?
    s
    • 2
    • 2
  • k

    kevin.cianfarini

    09/28/2021, 12:44 PM
    I have the following enum class that has a custom serializer
    @Serializable(with = RepresentedAreaSerializer::class)
    enum class RepresentedArea(override val value: String) : StringEnum {
      Alaska("AK"),
      Alabama("AL"),
      AmericanSamoa("AS")
      ...
    }
    
    object RepresentedAreaSerializer : StringEnumSerializer(RepresentedArea.values())
    
    abstract class StringEnumSerializer<T>(
      enumValues: Array<out T>,
    ) : KSerializer<T> where T : StringEnum, T : Enum<T> {
    
      private val enumMap = enumValues.associateBy { it.value }
    
      override val descriptor get() = PrimitiveSerialDescriptor("StringEnumSerializer", PrimitiveKind.STRING)
      override fun serialize(encoder: Encoder, value: T) = encoder.encodeString(value.value)
      override fun deserialize(decoder: Decoder): T = checkNotNull(enumMap[decoder.decodeString()])
    }
    When I try to serialize this value with the following method, I get an error that
    Serializer for class 'RepresentedArea' is not found.
    @Test fun foo() {
        val json = Json { prettyPrint = true}
        assertEquals("VA", json.encodeToString(RepresentedArea.Virginia)) // runtime error
      }
    The strange bit is that I can serialize it as a part of other object structures. For example, the following works for both serializing and deserializing.
    @Serializable class GetLegislatorsByAddressRequest(
      val streetAddress: String,
      val city: String,
      val state: RepresentedArea,
      val postalCode: String,
    )
    I'm a bit stuck on this error. Does anyone have any ideas what I'm doing wrong?
    • 1
    • 1
  • r

    Richard Gomez

    10/02/2021, 12:20 AM
    I'm trying to convert a
    JsonObject
    to
    Map<String, Any>
    , but am stumped on
    JsonPrimitive
    . It stores all values as
    String
    , so it doesn't seem possible to get a float/boolean/etc. unless you know its type ahead of time. Is there a (simpler) way to accomplish this?
    e
    • 2
    • 10
  • m

    Matthew Cachia

    10/06/2021, 4:35 PM
    I would like to apply a JsonTransformingSerializer to all kinds (Any?). I read through the guide but I still can't seem to connect he docs on how I can apply it. Is it something I should add in a serializermodule? Much appreciated
    s
    • 2
    • 3
Powered by Linen
Title
m

Matthew Cachia

10/06/2021, 4:35 PM
I would like to apply a JsonTransformingSerializer to all kinds (Any?). I read through the guide but I still can't seem to connect he docs on how I can apply it. Is it something I should add in a serializermodule? Much appreciated
s

sandwwraith

10/07/2021, 10:37 AM
It's not possible at the moment. You need to specify serializer for each type separately
m

Matthew Cachia

10/07/2021, 10:41 AM
Thanks @sandwwraith. I just discovered a workaround:
object JsonEleTransformer = ...

val jsonEle = json.parseToJsonElement("{...}")
val transformedJsonEle = json.decodeFromJsonElement(JsonEleTransformer, jsonEle)

val t:T = json.decodeFromJsonElement(transformedJsonEle)
It works. Thank you just the same.
s

sandwwraith

10/07/2021, 10:41 AM
Good idea!
View count: 7