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

    xenomachina

    08/29/2022, 7:38 PM
    Is there a timeline for when creating custom
    Decoder
    implementations will no longer be
    @ExperimentalSerializationApi
    ?
  • e

    Eugen Martynov

    08/30/2022, 10:56 AM
    I’m reading official documentation on GitHub, and it looks like I need to add
    SerialName
    to all implementations to serialise the sealed interface. However, when I try to test it, I see that serialiset is not found for the discriminator. Does it mean I have to define all subclasses when defining the serializable module?
    d
    p
    • 3
    • 14
  • n

    nikolaymetchev

    08/31/2022, 12:51 PM
    Hi, I feel like it should be possible to serialize a subclass of
    com.google.protobuf.GeneratedMessageV3
    automatically. Has somebody written a Contextual serializer that does that?
  • r

    RayeW47

    08/31/2022, 9:05 PM
    Hello, I'm just starting out on learning how to use KotlinX (and serdes in general) and I am running in to an issue I can't seem to understand how to solve. I have a
    @Serializable class A
    and I have a helper class for companions to automatically grab a file to deserialize something in to an
    A
    and put it in
    A(.Companion).INSTANCE
    . However, using
    .INSTANCE
    gets a bit annoying to use and looks kind of gross, so I am trying to convert
    A
    in to a
    @Serializable sealed interface A
    , so that
    A.Companion
    can be an
    A
    and I can simply reference
    A
    rather than
    A(.Companion).INSTANCE
    . I can't seem to understand enough to get this working with a
    sealed interface
    , I keep running in to polymorphism errors or NPEs if I try to delegate similar to how I do in
    Loader
    , so I am here for help. Here's a minimum example.
    abstract class Loader<T>(val type: StringFormat, val filePath: String, val serializer: () -> KSerializer<T>, ) {
        val INSTANCE by lazy {
            type.decodeFromString(serializer(), File(filePath).readText())
        }
    }
    current
    @Serializable
    class A(val someProperty: Int) {
        companion object: Loader<A>(
            type = Json.Default, filePath = "./config/A-config.json", serializer = { A.serializer() }
        )
    }
    
    fun main() {
        A.INSTANCE.someProperty
    }
    goal
    @Serializable
    sealed interface A {
        val someProperty: Int
        companion object: Loader<A>(
            type = Json.Default, filePath = "./config/A-config.json", serializer = { A.serializer() }
        )
    }
    
    fun main() {
        A.someProperty
    }
  • x

    xxfast

    09/06/2022, 12:37 PM
    Where can i find the documentation/examples for Okio’s BufferedSource and BufferedSink with Kotlinx serialization ?
  • s

    spand

    09/06/2022, 2:16 PM
    I cant get the example of external serializers to compile. It fails with :
    Type mismatch: inferred type is ProjectSerializer but S
    erializationStrategy<TypeVariable(T)> was expected
    . What could I be doing wrong ?
    import kotlinx.serialization.*
    import kotlinx.serialization.json.*
    import kotlinx.serialization.encoding.*
    import kotlinx.serialization.descriptors.*
    
    // NOT @Serializable
    class Project(val name: String, val language: String)
    
    @Serializer(forClass = Project::class)
    object ProjectSerializer
    
    fun main() {
        val data = Project("kotlinx.serialization", "Kotlin")
        println(Json.encodeToString(ProjectSerializer, data))
    }
  • x

    xxfast

    09/06/2022, 10:50 PM
    Hi all, trying to use
    kotlinx-serialization-json-okio
    like this in
    commonMain
    class ValueStore<T: Any>(
      val path: Path,
      val serializer: Json = Json,
      ..
    ) {
      suspend inline fun <reified V: T> set(value: V?) = lock.withLock {
        stateFlow.emit(value)
        serializer.encodeToBufferedSink(value, FILE_SYSTEM.sink(path).buffer())
      }
    }
    And have a
    commonTest
    written up like
    private val store: ValueStore<Pet> = ValueStore(path = "test.json".toPath())
    
    @Test
    fun testWriteValue() = runTest {
      val mylo = Pet(name = "Mylo", age = 1, type = Cat)
      store.set(mylo)
      val actual: Pet? = store.get<Pet>()
      val expect: Pet = mylo
      assertSame(expect, actual)
    }
    This test is failing 🤔 Although, I can see the
    test.json
    file being created, but it is empty. Am I using this correctly? Full source here
    j
    • 2
    • 6
  • a

    Ayfri

    09/08/2022, 3:54 PM
    Hi, is there a way to serialize an enum as the ordinal without adding SerialName for each key ?
    e
    • 2
    • 3
  • e

    ephemient

    09/11/2022, 12:06 AM
    Is it just me or is Json.decodeFromBufferedSource much slower than Json.decodeFromStream or Json.decodeFromString?
    j
    • 2
    • 10
  • j

    Jan Skrasek

    09/11/2022, 12:45 PM
    I want to utilize combined open and closed polymorphism, I have this class tree:
    // in library
    @Serializable
    interface Base
    
    // in user code
    sealed interface All : Base {
       @Serializable
       object A : All
    
       @Serializable
       data class B(...) : All
    }
    Ideally, I'd like to register as a subclass only the All type and not every children (A, B, ...). Do I miss something or it is not possible?
  • a

    Ayfri

    09/17/2022, 2:31 AM
    Hi, I'm trying to deserielize content using ktor and kotlinx.serialization, and I'm getting a very weird
    Illegal Input
    when I get a response that is an empty array, so just
    []
    , that should totally not create that error right ?
    d
    • 2
    • 5
  • x

    xxfast

    09/18/2022, 4:40 AM
    Hi all. I'm getting
    kotlinx.serialization.json.internal.JsonEncodingException: Value of type 'kotlinx.serialization.Polymorphic<IdType>' can't be used in JSON as a key in the map. It should have either primitive or enum kind, but its kind is 'OPEN'.
    where
    interface IdType : Parcelable {
      val name: String
    }
    
    enum class PersonIdType : IdType {
      GIVEN_NAME, MIDDLE_NAMES, FAMILY_NAME
    }
    
    enum class VehicleIdType : IdType {
      PLATE_NUMBER, VIN, ENGINE_NUMBER,
    }
    is this a known limitation? 🤔
    d
    • 2
    • 3
  • b

    Ben Woodworth

    09/22/2022, 4:04 AM
    I'm curious, is there a rationale for having only read-only JsonElement classes, and not mutable versions? Asking because of this issue on my own kxa format implementation requesting mutable elements: here
    • 1
    • 1
  • c

    cypher121

    09/25/2022, 8:50 AM
    Is there anywhere that details the specs for serializer structures? stuff like "polymorphic serializer's element 0 is expected to be the type name, and element 1 is the value. elements of value's descriptor are sealed subclasses, if any"
    d
    e
    x
    • 4
    • 18
  • c

    cypher121

    09/25/2022, 8:58 AM
    also, can MetaSerializable annotations be InheritableSerialInfo?
    d
    • 2
    • 1
  • l

    louiscad

    09/27/2022, 6:23 AM
    Could the following error message be linked to kotlinx.serialization? The
    NoSuchMethodError
    occurs when I try to use the
    copy
    function on a
    @Serializable
    data class
    that has one enum, one
    ULong
    , and one
    Long
    .
    java.lang.NoSuchMethodError: No virtual method copy-2TYgG_w(blablabla)_*blablabla*_
  • o

    Ovsyannikov Alexey

    09/27/2022, 9:59 AM
    Hello, I am looking for XML serial format and got several recommendations about https://github.com/pdvrieze/xmlutil . Do anybody knows, does this library use/support stream parsing of xml's or not?
    k
    • 2
    • 1
  • m

    martmists

    09/28/2022, 11:25 AM
    Hi, someone told me to ask here about serialization; I have several dozen formats of packets to send over USB, and I'm unsure how to define the classes to easily (de-)serialize them to/from a ByteArray/UByteArray send them over libusb from Kotlin/Native. How would I approach this?
    e
    • 2
    • 8
  • j

    Jorge Bo

    09/28/2022, 1:49 PM
    Hi Is there any way to map dynamic keys? I have this piece of json, in which keys varies, i used to make use of groovy to parse those keys bug now we are moving to ktor.
    flights_information": {
                    "OD_CUNMIA_01_20221111": {
                        "CPA_1": {
                            "FL00GH8001": {
                                "arrival_information": {
                                    "airport_reference_id": "MIA_0",
                                    "change_day_indicator": "0",
                                    "date": "2022-11-11",
                                    "date_of_week_name": "Friday",
                                    "time": "17:30:00"
                                },
    e
    c
    • 3
    • 5
  • j

    Javier

    09/29/2022, 12:36 PM
    When all compiler APIs become stable (FIR and so on), Kotlin Gradle Serialization plugin would be outside the Kotlin repo and having its own version? Serialization libraries are under kotlinx repo with its own version, I would expect that in the future for the plugin too
    v
    e
    • 3
    • 4
  • h

    Hrafn Thorvaldsson

    09/30/2022, 5:13 PM
    I have a question in regards to behavior differences when deserializing either raw
    String
    and
    JsonObject
    for target type classes not marked with the @Serializable annotation, and if this behavior difference is expected. Please observe the following data class:
    @Serializable
    data class Test(val value: Int)
    and the following manual construction of a JsonObject:
    val jsonObject = buildJsonObject {
       put("version", 1)
    }
    As expected when executing either
    Json.decodeFromJsonElement<Test>(jsonObject)
    or
    Json.decodeFromString<Test>(jsonObject.toString())
    the output is an instance of
    Test(value=1)
    . If the
    @Serializable
    annotation is removed from the class
    Test
    and a manual
    KSerializer
    for the class is created to handle the mapping:
    class TestSerializer: KSerializer<Test> {
    	override val descriptor: SerialDescriptor
    		get() = buildClassSerialDescriptor("test") {
    			element<Int>("version")
    		}
    
    	override fun deserialize(decoder: Decoder): Test {
    		return decoder.decodeStructure(descriptor) {
    			val version = decodeIntElement(
    				descriptor,
    				descriptor.getElementIndex("version")
    			)
    			Test(version)
    		}
    	}
        // .... omitting serialize() method
    }
    then executing
    Json.decodeFromJsonElement(TestSerializer(), jsonObject)
    will work like before and the output is an instance of
    Test(value=1)
    just as before. However executing
    Json.decodeFromString(TestingSerializer(), jsonObject.toString())
    will result in an exception:
    Unexpected JSON token at offset 1: Unexpected symbol 'v' in numeric literal at path: $
    kotlinx.serialization.json.internal.JsonDecodingException: Unexpected JSON token at offset 1: Unexpected symbol 'v' in numeric literal at path: $
    JSON input: {"version":1}
    Is this the expected behavior, and if so what is causing the string traversal to fail while the
    JsonObject
    is not affected?
    • 1
    • 3
  • n

    Nathan

    10/03/2022, 8:03 PM
    Issue with polymorphism and KMM: Setup is
    interface IFoo 
    
    @Serializable
    class FooA: IFoo
    
    @Serializable
    class FooB: IFoo
    val myJson = Json {
        ignoreUnknownKeys = true
        isLenient = true
        explicitNulls = false
        encodeDefaults = false
        serializersModule = SerializersModule {
            polymorphic(IFoo::class, FooA::class, FooA.serializer())
            polymorphic(IFoo::class, FooB::class, FooB.serializer())
        }
    }
    val listOfFoo = myJson.decodeFromString<<List<IFoo>>(...)
    The above ^ works fine in the Android code, but errors out when called from iOS:
    `kotlinx.serialization.SerializationException: Serializer for class ‘IFoo’ is not found.
    Mark the class as @Serializable or provide the serializer explicitly.
    On Kotlin/Native explicitly declared serializer should be used for interfaces and enums without @Serializable annotation`
    Is there a step that I am missing with setting up the SerializersModule to make it compatible with iOS? Again, this works perfectly fine from the Android Versions: • Kotlin: 1.7.10 • Kotlin serialization: 1.4.0 ◦ org.jetbrains.kotlinx:kotlinx-serialization-core ◦ org.jetbrains.kotlinx:kotlinx-serialization-json EDIT: https://kotlinlang.slack.com/archives/C7A1U5PTM/p1601187298013400 I found this older post with someone asking the same question and they seemed to solve it by downgrading ?
    k
    • 2
    • 2
  • s

    Stylianos Gakis

    10/04/2022, 11:56 AM
    Using kotlinx.serialization utilities for constructing JSON representations, I wonder, I got an incoming type with the signature
    Map<String, Any?>
    and I want to turn it into JSON to then pass somewhere else. With the type-safe builders I only see that I can do stuff like
    put(key:Any, value: JsonElement)
    but I don’t know how to turn my
    Any? -> JsonElement
    . I can do stuff like
    fun Any.toJsonElement() : JsonElement {
      when(this) {
        is Map<*, *> -> ...
        is Collection<*> -> ...
      }
    }
    and so on but I’ll most definitely do it wrong so I was looking if there’s some API I’m missing here.
    m
    e
    r
    • 4
    • 8
  • z

    zt

    10/04/2022, 9:08 PM
    Is there any simple way to use the ordinal of an enum instead of the name for serializing/deserializing?
    e
    • 2
    • 3
  • z

    zt

    10/04/2022, 9:46 PM
    I've got this data class which works for my data, but I wanna change it up some so its easier to work with. I need to make it so a value of
    1
    represents it being present, and if its null then its not present. That way it can just be a list of the present `Feature`s
    @OptIn(ExperimentalSerializationApi::class)
    @Serializable
    data class SearchFilter(
        val sortBy: SortBy? = null,
        val filters: List<Filter>
    ) {
        @Serializable
        data class Filter(
            val uploadDate: UploadDate? = null, // ignore these
            val type: Type? = null, // ignore these
            val duration: Duration? = null, // ignore these
            val hd: Int? = null,
            @ProtoNumber(14)
            val uhd: Int? = null,
            val subtitles: Int? = null,
            val creativeCommons: Int? = null,
            @ProtoNumber(15)
            val spherical: Int? = null,
            @ProtoNumber(26)
            val vr: Int? = null
        )
    }
    
    @Serializable
    enum class Feature {
        LIVE,
        UHD,
        HD,
        SUBTITLES,
        CREATIVE_COMMONS,
        /** 360° video */
        SPHERICAL,
        VR
    }
    d
    e
    • 3
    • 4
  • r

    Ryunos

    10/05/2022, 3:54 PM
    Hi, is there a way to parse a string containing JSON to a list of associations key to value? I would like to check for duplicate keys in a JSON using such a list so a Map would not help me
    j
    • 2
    • 7
  • j

    Jan Skrasek

    10/07/2022, 7:28 AM
    Why those "default" R8 rules are not bundled directly in the library? Is there any reason or motivation not to do it? thx
  • r

    Ryunos

    10/09/2022, 4:58 PM
    I’m trying to run the tests on the project, using the jvm. Unfortunately, I keep having this error:
    > Task :kotlinx-serialization-core:compileKotlinJvm FAILED
    e: Module java.base cannot be found in the module graph
    I thought it was a problem with my configuration but I tried using version 1.8, 11 and 17 for java and nothing worked. Are there contributors out here who could help me?
    e
    • 2
    • 1
  • r

    rattleshirt

    10/11/2022, 10:58 AM
    Hi, is it possible with kotlinx to deserialize an array with nested cbor encoded data items contained within a map? For example:
    text(10)
      "nameSpaces"
    map(1)
      text(3)
        "key"
      array(10)
        encoded cbor data item, tag(24)
          bytes(82)
            ...
    • 1
    • 1
  • d

    Dylan

    10/11/2022, 3:28 PM
    Hi there, I'm using Retrofit with Serialization on Android. I'm trying to parse a Json object which contains a
    data
    object. The type of
    data
    is defined by
    isTypeA
    or
    isTypeB
    within the object itself. (See sample in thread). I was thinking about using a sealed class. Is there a way to specify using annotations that the type of the object should be defined by a value within that object?
    e
    • 2
    • 4
Powered by Linen
Title
d

Dylan

10/11/2022, 3:28 PM
Hi there, I'm using Retrofit with Serialization on Android. I'm trying to parse a Json object which contains a
data
object. The type of
data
is defined by
isTypeA
or
isTypeB
within the object itself. (See sample in thread). I was thinking about using a sealed class. Is there a way to specify using annotations that the type of the object should be defined by a value within that object?
Sample:
{
  "data": {
    "isTypeA": 1
    ...
  }
}
{
  "data": {
    "isTypeB": 1
    ...
  }
}
e

ephemient

10/11/2022, 3:39 PM
JsonContentPolymorphicSerializer
d

Dylan

10/11/2022, 5:43 PM
Oh great, thanks!
Mmh, turns out as useful as JsonContentPolymorphicSerializer is, it doesn't seem to support nullable types
View count: 1