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

    Robert Jaros

    07/27/2020, 3:16 PM
    In my humble opinion deprecating tons of API with level
    ERROR
    between subsequent releases misses the point of the deprecation at all 😉
    s
    • 2
    • 1
  • r

    Robert Jaros

    07/27/2020, 3:46 PM
    I'm using this kind of map
    customSerializers: Map<KClass<*>, KSerializer<*>>
    . In 0.20.0 I've used this function, which is now deprecated:
    @Deprecated(
        level = DeprecationLevel.ERROR,
        message = "This method was removed during serialization 1.0 API stabilization, " +
                "please use SerializersModule builder instead" // No replacement deliberately
    )
    public fun serializersModuleOf(map: Map<KClass<*>, KSerializer<*>>): SerializersModule = noImpl()
    How to use SerializersModule builder to create a SerializersModule from my customSerializers map?
    s
    • 2
    • 4
  • m

    Marcin Wisniowski

    07/28/2020, 11:29 PM
    How do I get a serializer for a typed List? I can't find it in the documentation.
    List<MyType>.serializer()
    obviously doesn't work.
    n
    e
    j
    • 4
    • 4
  • e

    Emil Orvik Kollstrøm

    07/29/2020, 5:29 AM
    How would you guys go about deserializing JSON objects that work like maps, where the properties are keys? For instance if you have something like this:
    {
      "thread": {
        "name": "Kotlin serialization question",
        "messages": {
          "xSDkj3402": {
            "text": "How would you guys..."
            "author" "kollstrom"
          }, 
          "-3krdjdfs03": {
            "text": "I see! The solution to all of your problems is..."
            "author": "helpful_person"
          }
        }
      }
    }
    Since the objects in “messages” in fact work like a map, how do you deserialize this into:
    data class Thread(
      val name: String,
      val messages: Map<String, Message>
    )
    
    data class Message(
      val text: String,
      val author: String
    )
    Now I know how to deserialize top-level objects into a map, but whenever I try to do the same thing on lower-level objects I always get strange behavior it seems. I’ve tinkered the most with Jackson, but open to #klaxon, kotlinx.serialization, Gson or whatever library that could make something like this work. Am I thinking about this weirdly? Is it easier if I don’t use maps but a class called Messages? I’ve tried that too, but still getting weird errors or not getting it to work correctly while going down that path, so very welcome to ideas.
    a
    s
    • 3
    • 4
  • m

    Mouaad

    07/29/2020, 2:28 PM
    Hello folks, I got this behavior from Intellij 2020.2
    s
    • 2
    • 1
  • c

    Christian Sousa

    07/29/2020, 3:53 PM
    Hey guys, I’m having troubles with the following serializer. What I’m trying to get:
    private var parser = kotlinx.serialization.json.Json(JsonConfiguration.Stable.copy(ignoreUnknownKeys = true))
    var stringToParse = "{\"gvlSpecificationVersion\":2}"
    var parsedReturn: VendorList = parser.parse(VendorList.serializer(), stringToParse)
    My structure is the following:
    @Serializable
    abstract class VendorList(
        open var lastUpdated: String?,
        open var gvlSpecificationVersion: Int?,
        open var vendorListVersion: Int?,
        open var tcfPolicyVersion: Int?,
        open var vendors: Map<String, Vendor>?,
    
        @Transient override var purposes: Map<String, Purpose>? = null,
        @Transient override var features: Map<String, Feature>? = null,
        @Transient override var specialFeatures: Map<String, Feature>? = null,
        @Transient override var specialPurposes: Map<String, Purpose>? = null,
        @Transient override var stacks: Map<String, Stack>? = null
    ): Declarations(
        purposes = purposes,
        features = features,
        specialFeatures = specialFeatures,
        specialPurposes = specialPurposes,
        stacks = stacks
    )
    
    @Serializable
    open class Declarations(
        open var purposes: Map<String, Purpose>?,
        open var specialPurposes: Map<String, Purpose>?,
        open var features: Map<String, Feature>?,
        open var specialFeatures: Map<String, Feature>?,
        open var stacks: Map<String, Stack>?
    )
    
    @Serializable
    data class Overflow (
        var httpGetLimit: Int
    )
    
    @Serializable
    data class Vendor(
        var purposes: List<Int>,
        var legIntPurposes: List<Int>,
        var flexiblePurposes: List<Int>,
        var specialPurposes: List<Int>,
        var features: List<Int>,
        var specialFeatures: List<Int>,
        var policyUrl: String,
        var deletedDate: @ContextualSerialization Any?,
        var overflow: Overflow?,
        override var id: Int,
        override var name: String
    ): GVLMapItem
    
    interface GVLMapItem {
        var id: Int
        var name: String
    }
    
    @Serializable
    data class Purpose(
        var description: String,
        var descriptionLegal: String,
        override var id: Int,
        override var name: String
    ): GVLMapItem
    
    @Serializable
    data class Feature(
        var description: String,
        var descriptionLegal: String,
        override var id: Int,
        override var name: String
    ): GVLMapItem
    
    @Serializable
    data class Stack(
        var purposes: List<Int>,
        var specialFeatures: List<Int>,
        var description: String,
        override var id: Int,
        override var name: String
    ): GVLMapItem
    I’m getting the following:
    kotlin.Throwable: Key type is missing in the map.
    Any help would mean a lot! Thanks!
    s
    • 2
    • 1
  • e

    efemoney

    07/30/2020, 11:14 PM
    @sandwwraith not sure if I’m running into a compiler bug or its desired behavior but I have a somewhat complex heirarchy I’m trying to serialize with an interface at its apex. Let me see if I can do this justice but my graph looks like:
    interface Field<Value> {...}
    
    interface InputField<InputT> : Field<InputT> {...}
    interface SelectorField<ValueT> : Field<ValueT> {...}
    
    abstract class NumberField : InputField<Number> {...}
    abstract class BooleanField : SelectorField<Boolean> {...}
    
    @Serializable
    data class NumberFieldImpl(...): NumberField()
    
    @Serializable
    data class BooleanFieldImpl(...): BooleanField()
    Also I have a custom _map_:
    // Need to add serializable on base class else compiler complains
    @Serializable
    abstract class MapBackedContainer<K, V>(val storage: MutableMap<K, V>) : MutableMap<K, V> by storage
    
    @Serializable // Currently fails compile, message below
    class FieldContainer : MapBackedContainer<String, Field<*>>
    
    @Serializable // This one has no errors, ActionImpl is non generic and annotated with @Serializable
    class ActionContainer : MapBackedContainer<String, ActionImpl>
    FieldContainer
    currently fails compile with the message “Serializer for element of type Any? has not been found. To use context serializer as fallback, explicitly annotate element with @Contextual”. I tried adding
    @Serializable
    on the intermediate abstract classes of
    Field<*>
    but the issue is the same. Same with adding
    @Contextual
    on the Field<*> generic parameter of FieldContainer.
    d
    s
    • 3
    • 13
  • j

    janvladimirmostert

    08/02/2020, 10:10 PM
    what should i be using for encoder in the ListSerializer?
    ListSerializer(ListingStateVO.serializer()).serialize(
    				encoder = ???,
    				value = it
    			)
    r
    • 2
    • 6
  • a

    andylamax

    08/02/2020, 10:51 PM
    What is the current state of kotlinx.serializationi? More importantly what is the current state on seralizing inline classes?
    👀 1
    ➕ 4
    j
    • 2
    • 5
  • i

    ilyagulya

    08/03/2020, 11:46 AM
    Hello, guys. I'm trying to deserialize such polymorphic json structure using custom KSerializer:
    {
      "data": {
        "type1": [
          {
            "id": 1,
            "payload": {
              "fieldA": "123",
              "fieldB": "321"
            }
          }
        ],
        "type2": [
          {
            "id": 1,
            "payload": {
              "fieldC": "789",
              "fieldD": "101112"
            }
          }
        ]
      }
    }
    And I want to get this as result:
    Map<String, List<Item>>
    where key is
    type1, type2
    and value list item is:
    data class Item(
        val id: Int,
        val payload: ItemPayload
    )
    sealed class ItemPayload {
        data class PayloadOne(
            val fieldA: String,
            val fieldB: String
        )
    
        data class PayloadTwo(
            val fieldC: String
            val fieldD: String
        )
    }
    Right now I'm thinking about to deserialize the JSON to intermediate data class (which has
    JsonObject
    instead of
    ItemPayload
    ), then determine which serializer do I need to use on each particular item and then deserialize the
    JsonObject
    to exact
    ItemPayload
    based on map key (
    type1, type2
    ) But I don't understand how can I deserialize
    JsonObject
    inside the
    KSerializer
    .
    j
    n
    • 3
    • 10
  • n

    Narek Mailian

    08/03/2020, 7:46 PM
    Hey, I'm trying to serialize some polymorphic JSON using serialization, and I get everything to work when the polymorphic objects are contained in an array or wrapped in another object, but when the polymorphic object is at top-level, it won't work and I won't get any "type"-key. The docs say that I can use PolymorphicSerializer to stringify, and using that gives me the "type"-key, but I'm unsure how to use that since i'm using Ktor and I want to avoid the boilerplate of doing this at every call.respond(..). Has anyone done this and might give me some pointers? :)
    c
    • 2
    • 2
  • s

    savrov

    08/04/2020, 2:33 PM
    Hello, I’m trying to serialize a generic class 
    ApiResponse<T>
     with 
    kotlinx.serialization
    . So i’ve created a 
    ApiResponseSerializer
     class, with help of docs. But now i don’t understand how to use that serializer, since none of provided methods doesn’t seem to suit to me. That is the place where i need a help. My ApiResponse<T> is defined like:
    data class ApiResponse<T>(
        val data: T? = null,
        val error: ApiError? = null
    )
    And the regular usage (in KTOR server) is
    respond(
        HttpStatusCode.Created,
        ApiResponse(data = response.data)
    )
    I don’t know where i can “attach” my serializer to 
    data
     field of my 
    ApiResponse
     class. Thank you in advance.
    a
    n
    • 3
    • 3
  • b

    Brett Best

    08/05/2020, 6:09 AM
    After adding this to my buid.gradle file I’m getting an error when building:
    e: java.lang.NoClassDefFoundError: org/jetbrains/kotlin/com/intellij/openapi/util/io/JarUtil
    	at org.jetbrains.kotlinx.serialization.compiler.diagnostic.VersionReader.getVersionsFromManifest(VersionReader.kt:34)
    Has someone here seen this before?
    s
    • 2
    • 8
  • e

    efemoney

    08/06/2020, 11:33 AM
    Whats the simplest or quickest way to declare a serializer that wraps a string in a particular class? I have:
    data class Reference(val id: String)
    
    // appears in the json as just String
    ...
    "reference" : "the-reference-id"
    ...
    g
    • 2
    • 2
  • a

    altavir

    08/06/2020, 4:07 PM
    Are there any plans to decouple serialModule from serialization engine?
    s
    • 2
    • 10
  • d

    Daniele B

    08/07/2020, 4:18 PM
    for example in my case, the “err” field is not always there
    j
    • 2
    • 7
  • k

    Karlo Lozovina

    08/13/2020, 2:02 PM
    so what exactly is polymorphic serialization? I'm having trouble even understanding what the issue is 🙂
    a
    s
    • 3
    • 6
  • f

    frank

    08/14/2020, 3:34 AM
    [Solved] I'm testing with
    buildJson
    but is immutable and I can't add new JsonElements Any mutable alternative in Kotlin-serialization lib? My Scratch code:
    val files = buildJsonArray {
     ficheros.forEach {
      add(buildJsonObject {
          put("name", JsonPrimitive(it))
      })
     }
    }
    d
    • 2
    • 2
  • k

    Karlo Lozovina

    08/14/2020, 1:43 PM
    is there a way to skip repeating the
    @Serializable(with = ...)
    annotation on every field? Can I somehow specify my custom serializer for a class in a global way?
    d
    • 2
    • 2
  • f

    frank

    08/14/2020, 3:13 PM
    I'm testing the new version: 1.0 and I have seen the change of
    json{}
    to
    buildJsonObject{}
    @sandwwraith Why was the change made for a more verbose option? Is there any plan to make it less verbose? Sample:
    jsonArray { //version 0.20.0
     +"fic.sld"
     +json {
       "age" to 123
     }
    }
    
    buildJsonArray { //version 1.0
     add("fic.sld")
     add(buildJsonObject {
        put("age", JsonPrimitive(123))
     })
    }
    ➕ 2
    m
    d
    s
    • 4
    • 5
  • k

    Karlo Lozovina

    08/14/2020, 5:55 PM
    Currently I'm handling missing JSON fields with
    someField: SomeType? = null
    , is there a way without specifying
    null
    as default? For a nullable field, when it's missing I always want it set to
    null
    , so it seems a bit redundant...
    g
    • 2
    • 1
  • j

    Jeremy

    08/14/2020, 9:16 PM
    I keep running into err: "Cannot access 'Serializable': it is internal in 'kotlin.io'. I've searched previous messages and double checked my dependencies: • common = org.jetbrains.kotlinx:kotlinx-serialization-runtime-common:${Versions.serialization} • android = "org.jetbrains.kotlinx:kotlinx-serialization-runtime:${Versions.serialization}" • ios = "org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:${Versions.serialization}" plugin is applied metadata is set in settings.gradle
    e
    t
    • 3
    • 4
  • u

    ursus

    08/17/2020, 3:42 AM
    Hi, is serializationx faster than moshi with codegen -- in compile times?
    g
    p
    • 3
    • 7
  • t

    TwoClocks

    08/18/2020, 4:41 AM
    So if I have two message in one ByteArray (Say I did a network read and got back 2 messages at once), how does the decoder tell me how many bytes were consumed in the byte array? How do I decode the second message?
    • 1
    • 1
  • g

    gildor

    08/18/2020, 7:57 AM
    Is there any reason why
    kotlinx-serialization-core
    is not format agnostic? All other formats were moved to own dependencies except Json and it’s never was clear for me why, so now it’s impossible to replace bundled Jsom implementation with own version, they will always available side by side, or if json is not used at all. I understand it’s not a big deal in terms of bytecode, it more about API surface, even if it 95% cases used only as json, why not just create dependency for it:
    kotlinx-serialization-json
    It’s rc already, probably too late, but maybe keep
    kotlinx-serialization-core
    and reintroduce something like
    kotlinx-serialization
    or again
    runtime
    which would include only annotations and basic utilities, no formats
    ➕ 7
    v
    • 2
    • 3
  • k

    Karlo Lozovina

    08/18/2020, 3:02 PM
    has
    import kotlinx.serialization.json.JsonDecodingException
    been moved or renamed in 1.0.0-RC?
    v
    • 2
    • 1
  • k

    Karlo Lozovina

    08/18/2020, 3:17 PM
    also, after upgrading to 1.0.0-RC I'm getting
    Back-end (JVM) Internal error: wrong bytecode generated
    errors... any idea where to start with that one? (Java/Kotlin newb here)
    j
    v
    • 3
    • 15
  • a

    Antoine Gagnon

    08/18/2020, 3:38 PM
    Hi! I’ve updated Kotlin to 1.4, and serialization to 1.0.0-RC and I’m getting this:
    Your current kotlinx.serialization core version is too low, while current Kotlin compiler plugin 1.4.0 requires at least 1.0-M1-SNAPSHOT. Please update your kotlinx.serialization runtime dependency.
    Any idea what’s going on?
    b
    s
    +3
    • 6
    • 12
  • i

    Ian

    08/18/2020, 4:31 PM
    I've got a few classes that are essentially wrappers around `ByteArray`s, which I understand ProtoBuf serialization can serialize efficiently (rather than treating them as a list of bytes as the CBOR and Json do). I've been trying to create a custom KSerializer that will do this but keep getting runtime errors. In this case the wrapper class is called
    ByteArraySegment
    - this is what I've tried (I suspect the issue may be the
    descriptor
    I'm using, but I'm not sure how I should be doing it):
    @Serializer(forClass = ByteArraySegment::class)
    companion object : KSerializer<ByteArraySegment> {
        override val descriptor: SerialDescriptor
            get() = ByteArraySerializer().descriptor
    
        override fun serialize(encoder: Encoder, value: ByteArraySegment) {
            encoder.encode(ByteArraySerializer(), value.asArray)
        }
    
        override fun deserialize(decoder: Decoder): ByteArraySegment {
            return ByteArraySegment(decoder.decode(ByteArraySerializer()))
        }
    }
    I've explained the problem in more detail on Reddit but nobody has been able to suggest a solution yet, would greatly appreciate any suggestions.
    t
    • 2
    • 1
  • j

    jw

    08/18/2020, 6:58 PM
    It is safe to operate with instances of
    StringFormat
    and call its methods.
    Just to be clear, this means so long as we're simply accepting a
    StringFormat
    in an API it's safe to
    OptIn
    to this experimental annotation to disable the warning and this is guaranteed to be compatible? It's only experimental to subtype
    StringFormat
    (and
    BinaryFormat
    )?
    v
    • 2
    • 1
Powered by Linen
Title
j

jw

08/18/2020, 6:58 PM
It is safe to operate with instances of
StringFormat
and call its methods.
Just to be clear, this means so long as we're simply accepting a
StringFormat
in an API it's safe to
OptIn
to this experimental annotation to disable the warning and this is guaranteed to be compatible? It's only experimental to subtype
StringFormat
(and
BinaryFormat
)?
v

Vsevolod Tolstopyatov [JB]

08/19/2020, 11:13 AM
Yes, exactly
👍 1
View count: 2