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

    Kris Wong

    12/10/2019, 3:36 PM
    it seems most json APIs expect the type to be known in order to read the value
    p
    j
    • 3
    • 7
  • a

    ankushg

    12/11/2019, 3:54 AM
    Does anyone have an example of using an
    expect typealias
    as a member of a
    data class
    that can be serialized?
    ⬆️ 1
    g
    • 2
    • 1
  • d

    dambakk

    12/11/2019, 12:35 PM
    Hi! I have started a new multiplatform project in IDEA (kotlin version 1.3.61), added the classpath, added
    id("kotlinx-serialization") version "1.3.61"
    to the plugins block and
    implementation(serialization("-common"))
    dependency to commonMain. Then I try to annotate a data class with
    @Serializable
    and IDEA says it fine, but when running gradle build it says
    Cannot access 'Serializable': it is internal in '<http://kotlin.io|kotlin.io>'
    . It seems similar to this issue: https://github.com/Kotlin/kotlinx.serialization/issues/395 but here the solution was to add the plugin to the plugin block - which I have already done. Any suggestion what might cause this?
    t
    • 2
    • 15
  • a

    ankushg

    12/11/2019, 7:33 PM
    I'm working in a multiplatform project where we have a few
    actual typealias MyClass = String
    for some platforms, while using
    actual data class MyClass(val someVal: String)
    on other platforms. We also have an
    expect val MyClassSerializer: KSerializer<MyClassSerializer>
    which we set equal to either
    StringSerializer
    or the generated serializer for the data class. We declare
    contextual(MyClass::class, MyClassSerializer)
    in our common serialization context. On platforms where we typealias to Strings, we get a
    SerializerAlreadyRegisteredException: Serializer for class String already registered in this module
    , even though our
    MyClassSerializer
    points to the built-in
    StringSerializer
    . Is there a way to avoid this error? • I see the
    overwriteWith
    option, but it feels scary to use this since I'd be overwriting behavior for ALL Strings. It seems easy to declare a custom serializer for a type without realizing that this might change behavior for every String in your app. • My understanding is that using an inline class instead of typealias might help here, but I'm not sure about the state of inline classes in multiplatform. • Can I contextually register a serializer if-and-only-if there isn't already one registered for the type? • Is it possible for the contextual registration to do an equality check on the
    KSerializer
    and not throw an error if we're just redeclaring the preexisting association?
    r
    • 2
    • 6
  • m

    marstran

    12/12/2019, 10:50 PM
    I have a data class in a module that is not dependent on kotlinx.serialization. Is there an easy way to make that class serializable in another module, without having to manually write the serializer?
    d
    n
    • 3
    • 9
  • s

    Shan

    12/15/2019, 11:13 PM
    Anyone know how I can resolve this StackOverflowError with the Kotlin compiler with Kotlinx.Serialization? I have an old multi-module project that I just upgraded to kotlin 1.3.61 from 1.3.30 and get this error when I try to build. I read it might have something to do with declaring a type alias in a different module from where it was originally declared, but not sure if that is relevant as it says this issue was fixed in 1.3.60.
    Untitled
    e
    • 2
    • 3
  • t

    tylerwilson

    12/16/2019, 3:04 PM
    I am attempting parse a complex JSON structure with a custom double serializer. Is there a simpler way to tell the parser to use a customer serializer instead of having to mark every property with
    @Serializable(with = CustomDoubleSerializer::class)
    since there are a large number of these formatted doubles. Thank you.
    • 1
    • 1
  • n

    Nagarajan

    12/16/2019, 5:01 PM
    I am trying to serialize a sealed class contains Option and i am using following Custom Serializer https://github.com/sksamuel/avro4k/blob/master/avro4k-arrow/src/main/kotlin/com/sksamuel/avro4k/arrow/OptionSerializer.kt While i serialize Option<Pair> getting following error
    class kotlin.Pair is not registered for polymorphic serialization in the scope of class kotlin.Any
    Find my sample code here
    @Serializable
        sealed class Fruit(@Serializable(OptionSerializer::class) var meta: Option<@Polymorphic Any>) {
            @Serializable
            data class Blueberry(@Serializable(OptionSerializer::class) val metaData: Option<Pair<String, String>> = Option.empty()) :
                Fruit(metaData)
        }
    
        @Serializable
        data class Basket(
            val blueberry: Fruit.Blueberry = Fruit.Blueberry()
        )
    
        @Test
        fun `Test Serialize Fruit`() {
            val basket = Basket(
                Fruit.Blueberry(Option.just(Pair("firstVal", "SecondVal")))
            )
            validateSerialize(basket, Basket.serializer())
        }
    • 1
    • 1
  • j

    jef

    12/16/2019, 10:16 PM
    how would i do something like this? https://stackoverflow.com/questions/59331257/jackson-deserialization-with-no-type
    t
    • 2
    • 1
  • j

    jimn

    12/17/2019, 9:42 AM
    @Serializable
    data class RowBinMeta(val name: String, val coord: Array<Int>, val typ: /*an enum*/ TypeMemento)
    val meta: List<RowBinMeta> =  RowBinMeta.RowBinMetaList(elements)
    val out = Json(JsonConfiguration.Default).toJson( meta  )
    Exception in thread "main" kotlinx.serialization.SerializationException: Can't locate argument-less serializer for class kotlin.collections.List. For generic classes, such as lists, please provide serializer explicitly. what am i missing?
    f
    s
    • 3
    • 6
  • s

    Sujit

    12/18/2019, 12:14 AM
    I have a simple
    @Serializable
    class with lots of members like this:
    @Serializable
        class TooManyMembers {
            val mem1: Int? = null
            val mem2: Int? = null
            .
            .
            .
            val mem248: Int? = null
        }
    That's a class with 248 members. Instantiating this member with
    val obj = TooManyMembers()
    throws this error at runtime:
    Too many arguments in method signature in class file SerializationTests$TooManyMembers
    java.lang.ClassFormatError: Too many arguments in method signature in class file SerializationTests$TooManyMembers
    If I remove just one member, no more of that error. Is that really a limit (247) with numbers of members one can have in a
    @Serializable
    class? What can I do if I have an object with more members? 247 seems way too low. This is with
    0.14
    and kotlin
    1.3.61
    f
    • 2
    • 2
  • l

    lewis

    12/20/2019, 6:00 PM
    Is there a way to deserialise JSON to a
    Map
    ? I've tried just passing HashMap has a type but I'm just seeing
    Can't locate argument-less serializer for class java.util.HashMap. For generic classes, such as lists, please provide serializer explicitly.
    r
    • 2
    • 2
  • n

    nrobi

    12/23/2019, 2:20 PM
    Did anyone struggle with
    kotlinx-serialization
    ? I’m using
    0.14.0
    , and I’m gettin pretty randomly
    java.lang.NoClassDefFoundError:
    , some time it works, some time it doesn’t 🤷
    d
    • 2
    • 5
  • m

    molikuner

    12/23/2019, 2:25 PM
    Hey, I just ran into a weird issue with custom serializers. I have following code:
    class InlineSerializerTest {
        @Test
        fun `simple TestClass serialization test`() {
            val json = "\"test\""
            val parsed = Json.parse(TestClass.Companion, json)
            assertEquals(
                TestClass("test"),
                parsed
            )
        }
    }
    
    
    @Serializable(with = TestClass.Companion::class)
    data class TestClass(val a: String) {
    
        @Serializer(forClass = TestClass::class)
        companion object : TestSerializer {
            override val descriptor: SerialDescriptor = StringDescriptor
    
            // when removing this function the serialization crashes.
            override fun deserialize(decoder: Decoder): TestClass {
                return TestClass(decoder.decodeString())
            }
    
            override fun serialize(encoder: Encoder, obj: TestClass) = throw UnsupportedOperationException()
        }
    }
    
    interface TestSerializer: KSerializer<TestClass> {
        override fun deserialize(decoder: Decoder): TestClass {
            return TestClass(decoder.decodeString())
        }
    }
    As you can see in the companion object, I redefined the deserialize function with the same body as the extending interface. When removing this implementation the deserialization crashes:
    Invalid JSON at 0: Expected '{, kind: CLASS'
    kotlinx.serialization.json.JsonDecodingException: Invalid JSON at 0: Expected '{, kind: CLASS'
    	at kotlinx.serialization.json.internal.JsonReader.fail(JsonReader.kt:293)
    	at kotlinx.serialization.json.internal.StreamingJsonInput.beginStructure(StreamingJsonInput.kt:39)
    	... // if needed I can provide the full stack later
    Any idea how to resolve this? Whats really weird is that the error says that a
    class
    kind descriptor would be used, but String is definetly not a class kind type.
    • 1
    • 2
  • k

    Kris Wong

    12/23/2019, 5:26 PM
    it looks like a lot of serialization internals are leaking into my project's API. is there a way to suppress that?
    b
    • 2
    • 5
  • j

    jeggy

    12/30/2019, 12:30 AM
    I'm trying to build a complicated JSON object. But the
    JsonObjectBuilder
    doesn't have any
    suspend
    functions. What would then be the recomended way of building a JSON object across multiple coroutines?
    p
    z
    • 3
    • 3
  • g

    Gurupad Mamadapur [FH]

    01/03/2020, 1:43 PM
    Does serialization not support generics? I am working on a multiplatform project (Targetting Android and JS) -
    @Serializable
    class BaseResponse<T> {
    
        val data: T? = null
    
        @SerialName("status")
        val isSuccess: Boolean = false
    
        @SerialName("session")
        val isSessionExpire: Boolean = false
    
        @SerialName("message")
        val message: String = ""
    }
    Can this be serialized -
    BaseResponse<String>
    ? There is an error logged ->
    java.lang.UnsupportedOperationException: The only generic classes supported for now are standard collections
    got class class dto.BaseResponse (Kotlin reflection is not available)
    I did read the documentation regarding requiring a custom serializer in case of generics but wasn't able to understand it. Any help would be much appreciated.
    ⬆️ 1
    r
    • 2
    • 4
  • k

    Kris Wong

    01/07/2020, 3:05 PM
    has anyone seen this error before: java.lang.NoClassDefFoundError: Failed resolution of: Lkotlinx/serialization/internal/GeneratedSerializer? it's happening when running connected tests on Android.
    😕 2
    • 1
    • 6
  • h

    Hauke Radtki

    01/08/2020, 8:19 PM
    Is there any workaround for serializing inline classes (or UInt/UShort/UByte specifically). I know inline classes are not supported for serialization right now, but is there a way to make it work (no matter how verbose)?
    • 1
    • 2
  • j

    jw

    01/13/2020, 6:43 PM
    there is no mpp stream abstraction (yet)
    z
    • 2
    • 4
  • a

    agta1991

    01/18/2020, 7:06 PM
    Hi! Did anyone faced this exception before?
    UnknownFieldException: Unknown field for index -2
    I'm getting this when I try to use Mapper.unmap(serializer, map) call. I made a minimal reproduction code snipet.
    r
    • 2
    • 6
  • e

    Edward Taylor

    01/20/2020, 9:00 PM
    Hey all! I've got an event stream from JS (legacy library) into Kotlin. I've got data classes under sealed classes that I want to map from type names to serializers so that I can easily parse from an event to the correct object. Here are the classes:
    sealed class ManyHandsData: JSAction() {
            @Serializable
            data class handError(val message: String, val errorCode: Int): ManyHandsData()
    
            @Serializable
            data class DATA_INPUT(val openSensorInput: Int, val closeSensorInput: Int): ManyHandsData()
    
            @Serializable
            data class currentGripDidChangeExtended(val currentGrip: Int, val buttonSelected: Int, val currentButtonIndex: Int): ManyHandsData()
        }
    I've tried this:
    internal val handDataActionSerializers = listOf(
        JSAction.ManyHandsData.handError.serializer(),
        JSAction.ManyHandsData.DATA_INPUT.serializer(),
        JSAction.ManyHandsData.currentGripDidChangeExtended.serializer()
    ).associateBy { it.descriptor.name}
    which doesn't have the simple name. I was thinking maybe Delegates are the way to go (doing this for mapping js methods) but I'm struggling to think how to integrate that with data classes.. The goal would a mapping similar to above which allows me to retrieve a serializer by the string of an identifier (eg "DATA_INPUT")
    • 1
    • 2
  • r

    ribesg

    01/27/2020, 10:12 AM
    Does anyone know if you can make AppCode see generated serializers? Or if there is an opened issue for that problem?
    l
    • 2
    • 2
  • b

    Big Chungus

    01/27/2020, 2:24 PM
    Also, @Transient does not seem to be working correctly on MPP expect/actual. I'm expecting a base class and adding extra transient field on one platform, however it still gets serialized
    s
    • 2
    • 3
  • d

    dambakk

    01/28/2020, 2:46 PM
    Hi! I am struggeling with some serialization and was hoping somebody could help.. I want to pass in a list of objects as a body to a (ktor) request. This is where I’m doing the serialization.
    val userIds: List<MemberInput> = listOf(...)
    val json: JsonElement = Json.nonstrict.toJson(MemberInput.serializer().list, userIds)
    <http://client.post|client.post><HttpResponse> {
                    header("Content-Type", "application/json")
                    header("Accept", "*/*")
                    body = json
    }
    This gives me an exception when setting it as the body to the request:
    java.lang.ClassCastException: kotlinx.serialization.json.JsonObject cannot be cast to java.lang.String
    . (I should be able to set the
    userIds
    as body out of the box, but for debugging purposes…) First; is this a kotlinx.serialization or a ktor issue? Secondly; what’s wrong? 🙂 I appreciate any help! 🙂
    n
    • 2
    • 6
  • t

    turansky

    02/04/2020, 7:31 AM
    Is there any non-internal analog for
    SerialClassDescImpl("MyClass")
    in
    0.14.0-1.3.70-eap-134
    ?
    n
    • 2
    • 2
  • s

    Shan

    02/04/2020, 6:59 PM
    Is there any way to define a serializer for a top-level list as a contextual serializer in a
    SerializersModule
    ?
    s
    • 2
    • 4
  • v

    vanniktech

    02/05/2020, 9:41 AM
    Has anyone hooked up kotlinx serialization with Spring Boot?
    l
    • 2
    • 1
  • n

    napperley

    02/06/2020, 10:57 PM
    Is it possible to handle polymorphic JSON structures (are JSON structures that change depending on what is sent as input) with KotlinX Serialization?
    s
    • 2
    • 5
  • m

    Marc Knaup

    02/10/2020, 8:35 AM
    What is the reasoning behind using
    fun serializer() =
    instead of
    val serializer get() =
    /
    val serializer =
    ? I’m working on a library which stands before a similar decision and would love to hear it :)
    s
    • 2
    • 2
Powered by Linen
Title
m

Marc Knaup

02/10/2020, 8:35 AM
What is the reasoning behind using
fun serializer() =
instead of
val serializer get() =
/
val serializer =
? I’m working on a library which stands before a similar decision and would love to hear it :)
s

sandwwraith

02/10/2020, 9:33 AM
mainly because of consistensy with
fun serializer(typeSerialzerOne: KSerializer, typeSerializerTwo: ...)
— such functions are generated for generic classes with type parameters
m

Marc Knaup

02/10/2020, 9:34 AM
Makes sense, thanks! So I’ll use
fun
to be forward-consistent in case I’ll have to do something similar 🙂
View count: 4