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

    Ryan Rolnicki

    11/17/2021, 8:53 AM
    How to serialize a reasonably complex type that is not in my control? I am interested in storing a Google Places API response, but there are a plethora of types that of course aren't marked as `@Serializable`; to avoid adding custom logic for each, is there an easy way to create the serializers as if I the classes had the annotation? Or is the best options to use a reflection based serialzer like gson?
    b
    e
    +1
    33 replies · 4 participants
  • j

    jean

    11/17/2021, 1:41 PM
    I’m working with a backend returning a
    value
    attribute as part of a json payload. That attribute can potentially be of any primitive type or null. I started with a custom serializer :
    class NullableAnySerializer : KSerializer<Any?> {
        override val descriptor: SerialDescriptor = // What should it be here?
    
        override fun serialize(encoder: Encoder, value: Any?) {
            when (value) {
                null -> encoder.encodeNull()
                is Float -> encoder.encodeFloat(value)
                is Boolean -> encoder.encodeBoolean(value)
                else -> throw IllegalStateException("unsupported type")
            }
        }
    
        override fun deserialize(decoder: Decoder): Any? {
            // What should it be here?
        }
    }
    I’m stuck at the level of
    descriptor
    and
    deserialize()
    what should I use in those places?
    d
    3 replies · 2 participants
  • r

    Richard Gomez

    11/18/2021, 3:07 AM
    Will there ever be an easy way to handle
    Map<String, Any>
    ? It's a legitimate use case that seems to have been dismissed outright. Saying "use JsonObject instead" but not providing any guidance is a recipe for frustration and buggy implementations: https://github.com/Kotlin/kotlinx.serialization/issues/296 https://github.com/Kotlin/kotlinx.serialization/issues/746 https://github.com/Kotlin/kotlinx.serialization/issues/1537 https://kotlinlang.slack.com/archives/C7A1U5PTM/p1632495920135600?thread_ts=1632392673.125200&amp;cid=C7A1U5PTM
    e
    b
    23 replies · 3 participants
  • s

    spierce7

    11/18/2021, 4:34 AM
    Is there a way to serialize an object where the type isn’t known at compile time? I’m getting this exception on Kotlin Native -
    kotlinx.serialization.SerializationException: Serializer for class 'Any' is not found.
    b
    1 reply · 2 participants
  • r

    Ruben Quadros

    11/20/2021, 7:06 PM
    Hi guys, any idea/progress about this? Thanks in advance! https://github.com/Kotlin/kotlinx.serialization/issues/614
    👍 1
    1 reply · 1 participant
  • b

    Ben Deming

    11/23/2021, 1:02 AM
    Hi there – I’m running into an unusual error linking against an Apple (iOS) framework built from a Kotlin MPP project after adding a dependency to
    kotlinx-serialization-json
    . The project: – contains
    androidMain
    ,
    commonMain
    , and
    iosMain
    sourceSets – built to a framework using the
    syncFramework
    task created by applying the Cocoapods plugin, and run using a pod post_install hook – already uses
    kotlinx-serialization-protobuf
    across all source sets already without incident Our Kotlin language version is 1.5.21. The serialization plugin is applied in this manner:
    plugins {
        kotlin("multiplatform")
        kotlin("native.cocoapods")
        kotlin("plugin.serialization") version "1.5.21"
    And the dependency on kotlinx-serialization-protobuf is defined in this manner:
    val commonMain by getting {
                dependsOn(designSystemMain)
                dependencies {
                    ...
                    implementation("org.jetbrains.kotlin:kotlin-stdlib-common")
                    ...
                    implementation("org.jetbrains.kotlinx:kotlinx-serialization-protobuf:1.2.1")
                    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.1")
                }
            }
    A serializable class is defined like so:
    @ExperimentalSerializationApi
    @Serializable
    data class AuthorizerRequestInfo(
        @SerialName("token")
        val token: String,
        @SerialName("client-id")
        val clientId: String,
    )
    Source in iosMain attempts encodes an instance of the data class in this manner:
    Json.encodeToString(
        serializer = serializer(),
        value = AuthorizerRequestInfo(
            token = ...,
            clientId = ...
        )
    )
    The iOS framework is successfully built using the
    syncFramework
    command, but a linker issue occurs when statically linking the framework into the application:
    Showing All Messages
    Ld [redacted]/[redacted].app/[redacted] normal (in target '[redacted]' from project '[redacted]')
        cd 
        ....
    Undefined symbols for architecture x86_64:
      "_kfun:kotlinx.serialization.json.JsonClassDiscriminator#<get-discriminator>(){}kotlin.String", referenced from:
          _kfun:kotlinx.serialization.json.internal#classDiscriminator__at__kotlinx.serialization.descriptors.SerialDescriptor(kotlinx.serialization.json.Json){}kotlin.String in [redacted](result.o)
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    We aren’t making use of class discriminator, note how ‘simple’ the
    AuthorizerRequestInfo
    class in question is, so I’m left kind of stumped. Interestingly, the tasks that compile our
    iosTest
    source set & links our unit test target for iOS completes successfully – we can spawn a simulator and run a test executable with them, without incident. Does anyone have guidance on how we can debug this further?
    1 reply · 1 participant
  • s

    snowe

    11/23/2021, 7:32 AM
    How would I go about encoding/decoding one type to another, where the second type just needs a few functions called to insert the elements. e.g: input:
    @Serializable
    data class ChangeOrderInput(
        val oldProposal: OldProposal,
        val newProposals: List<NewProposal>
    )
    output:
    @Serializable
    data class ChangeOrderUnit(
        val oldProposal: SingletonStore<OldProposal>,
        val newProposals: ListDataStore<NewProposal>,
    ) : RuleUnitData
    where
    ChangeOrderUnit
    will always be deserialized from
    ChangeOrderInput
    , never the other way around, and where SingletonStore/ListDataStores are created just by calling
    oldProposal.set()
    or
    newProposals.add()
    on the stores, with the element. e.g. the only difference between the objects are that the RuleUnit object has the objects contained in stores.
    r
    e
    37 replies · 3 participants
  • s

    snowe

    11/23/2021, 5:35 PM
    I guess my question above could be better asked. What is the kotlinx-serialization equivalent of Jackson's convertValue function?
    e
    2 replies · 2 participants
  • a

    Arpit Shukla

    11/28/2021, 4:55 AM
    How can I convert 
    Map<String, Any>
     to a data class using kotlinx.serialization?
    p
    1 reply · 2 participants
  • r

    rocketraman

    11/29/2021, 6:46 AM
    I have a closed polymorphic structure like this (only one subclass shown for simplicity):
    @Serializable
    sealed class Foo<out T> {
      @Serializable
      data class Bar<out T>(
        val value: T?,
      ): Foo<T>()
    }
    Json.encodeToString(Foo.Bar(true))
    works, but if it is wrapped inside another Serializable e.g.:
    @Serializable
    data class Whatever(val foo: Foo<Boolean>)
    Json.encodeToString(Whatever(Foo.Bar(true)))
    produces the error:
    Exception in thread "main" kotlinx.serialization.SerializationException: Class 'Boolean' is not registered for polymorphic serialization in the scope of 'Any'.
    Mark the base class as 'sealed' or register the serializer explicitly.
    d
    27 replies · 2 participants
  • h

    Halex

    11/29/2021, 12:11 PM
    Hello everybody! So I have this interesting use case that I cannot seem to be able to handle. I have a module with two interfaces,
    Base
    (which is sealed) and
    Data
    that extends it, and subclasses of
    Data
    that cannot be changed, and I have other modules where I can do anything. The comments in the code below should hopefully guide you.
    Data
    interface should be serialized taking into account only its text property (I use
    ConcreteData
    for deserializing). The issue is that while I can serialize arbitrary subclasses (represented by
    RandomData
    ) in the context of
    Data
    , I cannot seem to do it in the context of
    Base
    . Any help would be greatly appreciated!
    test_kt.cpp
    r
    4 replies · 2 participants
  • a

    Arpit Shukla

    11/30/2021, 4:57 AM
    Can someone help me with this? https://stackoverflow.com/questions/70164434/how-to-decode-a-json-string-to-a-given-kclass
    k
    4 replies · 2 participants
  • d

    delblanco

    11/30/2021, 8:43 AM
    Hi everybody! Is it possible to parse an empty string to null? Context: I’m trying to parse a response from an external version-check api. If version is up to date it returns a 200 response + empty json body. If the version is outdated it returns HTTP 200 + json body. Here is an oversimplified test:
    @Test
        fun test() {
            val voluntary = Json.decodeFromString<SerializableVersionCheckResponse?>("""
            |{
            |  "beheerCode": "VRIJWILLIGE_UPDATE",
            |  "bericht": "App moet geupdate worden"
            |}
            """.trimMargin()
            )
            assertNotNull(voluntary)
            assertEquals("VRIJWILLIGE_UPDATE", voluntary.beheerCode)
    
            val mandatory = Json.decodeFromString<SerializableVersionCheckResponse?>("""
            |{
            |  "beheerCode": "VERPLICHTE_UPDATE",
            |  "bericht": "Oewe telefoon is oud."
            |}
            """.trimMargin())
            assertNotNull(mandatory)
            assertEquals("VERPLICHTE_UPDATE", mandatory.beheerCode)
    
            val upToDate = Json.decodeFromString<SerializableVersionCheckResponse?>("")
            assertNull(upToDate)
        }
    The last decodeFromString fails with the following message:
    kotlinx.serialization.json.internal.JsonDecodingException: Expected start of the object '{', but had 'EOF' instead
    JSON input:
        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:479)
    d
    e
    7 replies · 3 participants
  • r

    Rafal

    12/01/2021, 1:10 PM
    Hi 👋 We have an api that can return
    {
      "number": 100
    }
    or
    {
      "number": "none"
    }
    depending on some conditions, how can I parse this kind of json if I want to have
    number: Int?
    as a result? If the json responds a
    String
    I wan’t the number to be
    null
    e
    1 reply · 2 participants
  • j

    JinYong Kim

    12/03/2021, 2:58 AM
    Hi everybody! i have a question. Can i use @Serializable annotation for java class?
    d
    3 replies · 2 participants
  • m

    Michal Havryluk

    12/03/2021, 10:11 AM
    Hello, is there a way to do JsonDiff (needed for PATCH request) as in library for example https://github.com/beyondeye/kjsonpatch (still mostly in Java). So method with two JSON elements and return value is one JSON element? Or the 3rd party library is the only option. Thanks.
    n
    2 replies · 2 participants
  • v

    v79

    12/04/2021, 4:37 PM
    I'm hitting an odd issue where a class can't seem to serialize itself, or at least it's not serializing its backing fields. It's a small class:
    @Serializable
    class GameState {
        var playerName = "Dougie McDougal"
        @Transient
        var saveFileName = "save1"
    
        suspend fun save() {
            println("Saving game state $saveFileName.gs.json")
            val gameStateJson = Json.encodeToString(this@GameState)
            val saveFile = applicationVfs["saves/$saveFileName.gs.json"]
            saveFile.write(gameStateJson.toByteArray())
        }
    }
    The serialized output is just
    {}
    - empty.
    playerName
    is not being serialised. Any thoughts?
    d
    3 replies · 2 participants
  • m

    mbonnin

    12/07/2021, 3:09 PM
    Does
    Json.decodeFromStream(InputStream)
    close the inputStream for me or should I wrap in
    use {}
    ?
    b
    3 replies · 2 participants
  • r

    rocketraman

    12/07/2021, 10:44 PM
    Is there an open source serializer for
    kotlin.time.Duration
    somewhere?
    1 reply · 1 participant
  • i

    ipolyzos

    12/08/2021, 2:32 PM
    hi - new to kotlin here and im trying to use it along with protobufs i have this schema
    message JEvent {
      string eventTime = 1;
      string eventType = 2;
      string productId = 3;
      string categoryId = 4;
      string categoryCode = 5;
      string brand = 6;
      string price = 7;
      string userId = 8;
      string userSession = 9;
    }
    and i generate the class, but when the code compiles i get
    /JEventKt.kt: (13, 5): JvmField has no effect on a private property
    object JEventKt {
      @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class)
      @com.google.protobuf.kotlin.ProtoDslMarker
      class Dsl private constructor(
        @kotlin.jvm.JvmField private val _builder: io.ipolyzos.models.Event.JEvent.Builder      <------------- COMPLAINS FOR THIS LINE HERE
      ) {
        companion object {
          @kotlin.jvm.JvmSynthetic
          @kotlin.PublishedApi
          internal fun _create(builder: io.ipolyzos.models.Event.JEvent.Builder): Dsl = Dsl(builder)
        }
    
        @kotlin.jvm.JvmSynthetic
        @kotlin.PublishedApi
        internal fun _build(): io.ipolyzos.models.Event.JEvent = _builder.build()
    r
    2 replies · 2 participants
  • p

    phldavies

    12/10/2021, 12:33 PM
    Is there any way to tell kotlinx.serialization that the class-discriminator for a polymorphic field is defined by a sibling field? i.e.
    {"eventType": "MyEventType": "event": { … /*MyEventType fields */ }
    or will we need a custom serializer for this?
    d
    5 replies · 2 participants
  • f

    FunkyMuse

    12/12/2021, 6:54 PM
    Hey guys, is it possible to use kotlinx serialization on Android without providing proguard rules in release mode? Something that moshi has with codegen
    e
    11 replies · 2 participants
  • r

    ribesg

    12/16/2021, 4:49 PM
    Well that is interesting
    /* In a module of a KMP library */
    @Serializable
    internal data class GetFileResponse(
        val url: String
    )
    
    // In the same module
        override suspend fun getFileUrl(fileId: FileId): String =
            http.get<GetFileResponse>("$baseUrl$file/$fileId") {
                useAuthentication()
            }.url
    
    /* In an iOS app using the aforementioned library */
            val url = try {
                fileApi.getFileUrl(fileId)
            } catch(t: Throwable) {
                log.error("Failed to get file url for file id $fileId: ${t.message}", t)
                return null
            }
    
    /* Logs when running */
    ERROR - Failed to get file url for file id blablabla: Fields [name, rating] are required for type with serial name 'whatever.whatever.internal.model.UpsertCandidateEvaluationPayload.CriteriaValue', but they were missing
    kotlinx.serialization.MissingFieldException: Fields [name, rating] are required for type with serial name 'whatever.whatever.internal.model.UpsertCandidateEvaluationPayload.CriteriaValue', but they were missing
    The model mentioned by the log is completely unrelated and defined in a completely different place in another dependency… wat I just updated to 1.6.0 then 1.6.10 from 1.5.31 so maybe it’s that I don’t know. Super weird bug and not sure what to do. Is it some kind of name/id/hashcode clash or something?
    1 reply · 1 participant
  • m

    Mendess

    12/18/2021, 1:23 PM
    Is it possible to define a deserializer for a class that can deserialize from 2 different unambiguous formats? Example:
    { "createdAt": 11112222333 }
    { "createdAt": { "seconds": 179879, "nanoseconds": 1201800000 } }
    class DateTime(....)
    
    @Serializable
    class Payload(val createdAt: DateTime)
    (serialization is not needed)
    d
    a
    22 replies · 3 participants
  • s

    Skolson5903

    12/20/2021, 6:36 PM
    Hoping someone has an answer for this one. I have a use case building a Map<String, JsonElement> where the values in the map are all JsonPrimitve from various basic types like String, Int, Float, etc. With a map name of jsonRow, using this:
    val json = Json { encodeDefaults = true }
    val jsonString = json.encodeToString(JsonObject(jsonRow))
    works fine in debug producing correct JSON. But release minified build gets this exception in the encodeToString call:
    Serializer for class 'x' is not found.
        Mark the class as @Serializable or provide the serializer explicitly.
        k9.k: Serializer for class 'x' is not found.
        Mark the class as @Serializable or provide the serializer explicitly.
    What should I change to correct this? I have proguard rules set up for explicit @Serializable data classes and they work fine. But I have no rule(s) for this "dynamic" encode use case and am not sure what "class 'x'" is so don't know what rule to try. Is it saying that it can't find the serializer for Map (class 'x' minified), even though that is the explicit type required by the JsonObject constructor? Any help/tips are appreciated, my searches for something like this are not finding good hits 🙂 This is serialization 1.3.1 and kotlin 1.6.10.
    e
    2 replies · 2 participants
  • h

    holgerbrandl

    12/22/2021, 9:22 AM
    Is there common multiplatform way to represent a json? I don't need the full serialization stack, I'm just asking about the data-structure. Before I was using https://github.com/stleary/JSON-java for years, but I guess this one does not work in a multiplatform context. I have built my own builder with https://github.com/holgerbrandl/jsonbuilder, but I'd love to migrate it away from JSON-java
    m
    b
    9 replies · 3 participants
  • a

    Ayfri

    12/23/2021, 8:44 PM
    Hi, how can I create a serializer for
    List<Pair<String, SomeClassWithSerializer>>
    (I really need a List of pair, not maps, as I have to change often key names) ? I have this code but it gives me a compiler error :
    class SnapshotListPairSerializer<K, V>(private val keySerializer: KSerializer<K>, private val valueSerializer: KSerializer<V>) :
    	KSerializer<SnapshotStateList<Pair<K, V>>> {
    	override val descriptor: SerialDescriptor = ListSerializer(PairSerializer(keySerializer, valueSerializer)).descriptor
    	
    	override fun serialize(encoder: Encoder, value: SnapshotStateList<Pair<K, V>>) {
    		encoder.encodeSerializableValue(ListSerializer(PairSerializer(keySerializer, valueSerializer)), value as List<Pair<K, V>>)
    	}
    	
    	override fun deserialize(decoder: Decoder): SnapshotStateList<Pair<K, V>> {
    		val list = mutableStateListOf<Pair<K, V>>()
    		val items = decoder.decodeSerializableValue(ListSerializer(PairSerializer(keySerializer, valueSerializer)))
    		list.addAll(items)
    		return list
    	}
    }
    PS :
    class SnapshotStateList<T> : MutableList<T>
    Error in thread
    3 replies · 1 participant
  • t

    Thiago

    12/27/2021, 9:23 PM
    Hi folks, I have a doubt here: why Kotlin Serialization plugin doesn't generate a proguard file with packages/classes to keep? I know this is out of library/plugin scope, but the plugin walk through classes looking for @Serializable annotation. It would be nice reusing this walk phase to "write" to a file or console packages/classes to keep. I think adding something like that will not be weight because can run in parallel with search annotation phase. If it is totally out of scope, how can I to create a compiler plugin to do something like that?
    m
    s
    +2
    18 replies · 5 participants
  • a

    altavir

    12/29/2021, 9:18 AM
    I am getting a new type of errors in 1.3.2:
    Receiver class kotlinx.serialization.json.internal.PolymorphismValidator does not define or inherit an implementation of the resolved method 'abstract void polymorphicDefaultDeserializer(kotlin.reflect.KClass, kotlin.jvm.functions.Function1)' of interface kotlinx.serialization.modules.SerializersModuleCollector.
    java.lang.AbstractMethodError: Receiver class kotlinx.serialization.json.internal.PolymorphismValidator does not define or inherit an implementation of the resolved method 'abstract void polymorphicDefaultDeserializer(kotlin.reflect.KClass, kotlin.jvm.functions.Function1)' of interface kotlinx.serialization.modules.SerializersModuleCollector.
    Does anybody know what could cause this?
    2 replies · 1 participant
  • s

    Sam Garfinkel

    12/30/2021, 7:38 PM
    Does the
    Kotlin.serialization
    library support serialization of references? I’d like to serialize a graph.
    🇳🇴 1
    e
    1 reply · 2 participants
Powered by Linen
Title
s

Sam Garfinkel

12/30/2021, 7:38 PM
Does the
Kotlin.serialization
library support serialization of references? I’d like to serialize a graph.
🇳🇴 1
e

ephemient

12/31/2021, 3:10 AM
https://github.com/Kotlin/kotlinx.serialization/issues/1147
:tnx: 1
View count: 13