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

    thana

    08/23/2019, 2:34 PM
    is there a way to parse a json string into a Map using kotlinx.serialization?
    s
    • 2
    • 3
  • s

    sandwwraith

    08/23/2019, 3:45 PM
    📣 kotlinx.serialization
    v0.12.0
    has been released! This release is binary compatible with Kotlin/Native 1.3.50. Some highlights: • Added wasm and linuxArm32Hfp Kotlin/Native targets to publication • Multiplatform serializer resolving from
    KType
    class (which can be obtained from typeOf() function). Doesn't work for user-defined generic classes, but works for standard collections. • JSON parser is more strict now: leading/trailing commas and other separators are prohibited. • JSON exceptions hierarchy has been reworked. Full changelog: https://github.com/Kotlin/kotlinx.serialization/blob/master/CHANGELOG.md#v0120--2019-08-23
    🎉 9
    🤩 11
    j
    • 2
    • 2
  • a

    ankushg

    08/27/2019, 3:47 AM
    Is there a built-in serializer for types like
    IntArray
    and
    LongArray
    when working in a multiplatform project?
    s
    • 2
    • 2
  • k

    kevin.cianfarini

    08/28/2019, 12:50 AM
    Is there any way to assign the root object in a response to be the one that's deserialized into an object?
    d
    • 2
    • 8
  • p

    Paulius Ruminas

    08/29/2019, 12:37 PM
    Hello, I get this error:
    e: java.lang.IllegalStateException: class NewImport has duplicate serial name of property feedId, either in it or its parents.
    when I'm annotating a sealed class with `@Serializable`:
    @Serializable
    sealed class FeedOperation(open val feedId: FeedId) {
    
        @Serializable
        data class NewImport(override val feedId: FeedId) : FeedOperation(feedId)
    
        @Serializable
        data class RedoImport(override val feedId: FeedId) : FeedOperation(feedId)
    
        @Serializable
        data class RemoveImported(override val feedId: FeedId) : FeedOperation(feedId)
    }
    Are there any workarounds for this?
    d
    • 2
    • 5
  • n

    Nikky

    08/30/2019, 8:07 PM
    with kotlin 1.3.50 and serialization 0.12.0 the following code stopped working:
    @Serializable
    data class SomeClass(
        var aInt: Int = 5
    ) {
        @Transient
        lateinit var rootDir: File
    }
    this fails with:
    This property is marked as @Transient and therefore must have an initializing expression
    the rootDir is in this case the full path to the workingdirectory on the users machine, it should not be serialized, it gets set first thing after deserialization but it seems that is no longer allowed
    🤔 2
    s
    • 2
    • 7
  • j

    Juanoterocas

    08/31/2019, 9:27 PM
    hi all I'm having troubles with List<T>, do I need to write serialization strategy for each List<CustomClass> inside other class? '''@Serializable data class User( var id: Long?, var email: String?, var lastName: String?, var username: String?, var name: String?, var password: String?, var phone: String?, //var origin: String? @ContextualSerialization var registrationDate:Date? = null, val userRoles :List<Role>, @ContextualSerialization var birthday: Date?= null )'''
    f
    d
    • 3
    • 14
  • a

    ansman

    08/31/2019, 11:06 PM
    I need to encode a Point(x, y) as
    [x, y]
    . There seems to be many ways of doing it. The simplest is to read it as a
    List<Float>
    but I’d like to avoid boxing the floats if possible on the JVM. There is
    beginStructure
    and
    beginCollection
    but no documentation on when to use either or.
    d
    • 2
    • 8
  • a

    ansman

    09/01/2019, 1:18 AM
    Is kotlin reflect needed for serialization? I’m getting this:
    kotlin.jvm.KotlinReflectionNotSupportedError: Kotlin reflection implementation is not found at runtime. Make sure you have kotlin-reflect.jar in the classpath
    
    	at kotlin.jvm.internal.ClassReference.error(ClassReference.kt:79)
    	at kotlin.jvm.internal.ClassReference.getSimpleName(ClassReference.kt:12)
    	at kotlinx.serialization.SerialKind.toString(Descriptors.kt:11)
    	at java.lang.String.valueOf(String.java:2994)
    	at java.lang.StringBuilder.append(StringBuilder.java:131)
    	at kotlinx.serialization.json.internal.StreamingJsonInput.beginStructure(StreamingJsonInput.kt:39)
    d
    f
    s
    • 4
    • 4
  • r

    russhwolf

    09/03/2019, 4:01 AM
    The following test is failing for me on Native. It throws a
    NullPointerException
    inside the
    unmap()
    call. Is this a limitation of the use of
    Mapper
    on native or am I doing something wrong?
    @Test fun mapCoders() {
        val foo = Foo("hello", 43110)
        val mapper = Mapper.default
    
        val map = mapper.map(Foo.serializer(), foo)
        assertEquals("hello", map["bar"])
        assertEquals(43110, map["baz"])
    
        val newFoo = mapper.unmap(Foo.serializer(), map)
        assertEquals(foo, newFoo)
    }
    
    @Serializable
    data class Foo(val bar: String, val baz: Int)
    s
    • 2
    • 2
  • p

    Paulius Ruminas

    09/03/2019, 8:50 AM
    Hello, I have encountered this exception when I upgraded serializer to 0.12.0 and kotlin to 1.3.50
    e: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    	at java.util.ArrayList.rangeCheck(ArrayList.java:657)
    	at java.util.ArrayList.get(ArrayList.java:433)
    	at org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationPluginDeclarationChecker.checkTypeArguments(SerializationPluginDeclarationChecker.kt:167)
    	at org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationPluginDeclarationChecker.checkType(SerializationPluginDeclarationChecker.kt:188)
    	at org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationPluginDeclarationChecker.analyzePropertiesSerializers(SerializationPluginDeclarationChecker.kt:155)
    	at org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationPluginDeclarationChecker.check(SerializationPluginDeclarationChecker.kt:44)
    	at org.jetbrains.kotlin.resolve.ModifiersChecker$ModifiersCheckingProcedure.runDeclarationCheckers(ModifiersChecker.java:272)
    	at org.jetbrains.kotlin.resolve.ModifiersChecker$ModifiersCheckingProcedure.checkModifierListCommon(ModifiersChecker.java:213)
    	at org.jetbrains.kotlin.resolve.ModifiersChecker$ModifiersCheckingProcedure.checkModifiersForDeclaration(ModifiersChecker.java:172)
    	at org.jetbrains.kotlin.resolve.DeclarationsChecker.process(DeclarationsChecker.kt:91)
    	at org.jetbrains.kotlin.resolve.BodyResolver.resolveBodies(BodyResolver.java:245)
    	at org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer.analyzeDeclarations(LazyTopDownAnalyzer.kt:225)
    	at org.jetbrains.kotlin.resolve.LazyTopDownAnalyzer.analyzeDeclarations$default(LazyTopDownAnalyzer.kt:60)
    	at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:111)
    	at org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:81)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:555)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.invoke(KotlinToJVMBytecodeCompiler.kt:82)
    	at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:107)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:546)
    	at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules$cli(KotlinToJVMBytecodeCompiler.kt:177)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:164)
    	at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:54)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:84)
    	at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.kt:42)
    	at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:104)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:349)
    	at org.jetbrains.kotlin.incremental.IncrementalJvmCompilerRunner.runCompiler(IncrementalJvmCompilerRunner.kt:105)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.compileIncrementally(IncrementalCompilerRunner.kt:237)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner.access$compileIncrementally(IncrementalCompilerRunner.kt:37)
    	at org.jetbrains.kotlin.incremental.IncrementalCompilerRunner$compile$2.invoke(IncrementalCompilerRunner.kt:79)
    	.....
    m
    • 2
    • 2
  • j

    Justin

    09/08/2019, 9:08 PM
    I could use some help on a tricky serialization issue. For context, I am using the current version of
    kotlinx.serialization
    in a multplatform project. The basic question is this: what is the best way to handle deserialization of Json when one of the field names (i.e. keys) is variable? I have put together a simple example to illustrate the problem:
    @Serializable data class UserData(val name: String)
    
    @Serializable
    data class User(
        val user_data: UserData, 
        val user_contributions: List<Contribution>
    ) {}
    
    interface Action {
        val id: String
    }
    
    @Polymorphic interface Content
    
    @Polymorphic interface Contribution : Action {
        val content: Content
    }
    
    @Serializable data class Mentor(
        override val id: String,
        
        @SerialName("mentorContent")
        override val content: MentorContent
    ) : Contribution {
        @Serializable data class MentorContent(val mentor: String, val mentee: String) : Content
    }
    
    @Serializable data class Judge(
        override val id: String,
        
        @SerialName("judgeContent")
        override val content: JudgeContent
    ) : Contribution {
        @Serializable data class JudgeContent(val judge: String, val judged: String) : Content
    }
    
    // Given this JSON:
    
    {
        "user_data": {
            "name": "Justin"
        },
        "user_contributions": [
            {
                "id": "1",
                "mentorContent": {
                    "mentor": "Lisa",
                    "mentee": "Phil"
                }
            },
            {
                "id": "2",
                "judgeContent": {
                    "judge": "Robert",
                    "judged": "Karen"
                }
            }
        ]
    }
    
    // This is the desired deserialized object:
    
    User(
        user_data = UserData(name = "Justin"),
        user_contributions = listOf(
            Mentor(
                id = "1",
                content = MentorContent(mentor = "Lisa", mentee = "Phil")
            ),
            Judge(
                id = "2",
                content = JudgeContent(judge = "Robert", judged = "Karen")
            )
        )
    )
    f
    m
    • 3
    • 11
  • j

    jush

    09/09/2019, 6:49 PM
    Does Kotlinx serialization support Windows 32 bits (
    mingw_x86
    target)? I keep getting this error:
    Unable to find a matching variant of org.jetbrains.kotlinx:kotlinx-serialization-runtime-native:0.12.0
    • 1
    • 1
  • l

    Laurenv

    09/11/2019, 9:52 AM
    Hi. Anyone know why the kotlinx-serialization-runtime-js lib has been been deprecated on npm? - https://www.npmjs.com/package/kotlinx-serialization-runtime-js I’m using serialization as part of my multiplatform project so I am currently left with a library that cannot find this dependency. Is the serialization library currently not setup to support multiplatform kotlin libraries?
    a
    b
    • 3
    • 5
  • f

    Fudge

    09/12/2019, 11:40 AM
    If I have a
    @Serializable
    class in a library:
    @Serializable class LibClass(val num :Int)
    Is it intended that I can't use it as serializable in a project that consumes the library?
    // Error! Serializer has not been found for LibClass
    @Serializable class MyClass(val nested : LibClass)
    d
    s
    • 3
    • 8
  • l

    leandro

    09/13/2019, 10:40 AM
    I’m seeing a weird behavior with v0.12.0 (and 0.11.1) where I’m trying to deserialize a data class, using
    Json.nonstrict
    with Retrofit 2.6.1. The field is a String, and with it on my class I receive the message:
    Field 'full_name' is required, but it was missing
    but if I remove it then I get:
    Encountered an unknown key full_name
    s
    • 2
    • 12
  • a

    ansman

    09/14/2019, 10:55 PM
    Is there any way to treat
    null
    in JSON as absent? I have a
    val foo: List<String> = emptyList()
    which fails to be parsed if
    foo
    is
    null
    in the JSON
    ➕ 3
    d
    • 2
    • 4
  • r

    robgray

    09/16/2019, 2:06 PM
    Hey all, I have a serializer class for integer backed enums. I'd like to handle de-serializing a case that doesn't exist (ex. 3) by returning null instead of throwing an exception. Is this possible?
    @kotlinx.serialization.Serializable(TestEnum.TestEnumSerializer::class)
        enum class TestEnum(val value: Int) {
            RED(0),
            GREEN(1),
            BLUE(2);
    
            @Serializer(forClass = TestEnum::class)
            companion object TestEnumSerializer : KSerializer<TestEnum> {
                private val map = values().associateBy(TestEnum::value)
    
                override val descriptor: SerialDescriptor
                    get() = StringDescriptor
    
                override fun deserialize(decoder: Decoder): TestEnum {
                    return map.getValue(decoder.decodeInt())
                }
    
                override fun serialize(encoder: Encoder, obj: TestEnum) {
                    encoder.encodeInt(obj.value)
                }
            }
        }
    ➕ 1
    n
    t
    • 3
    • 6
  • a

    ansman

    09/16/2019, 6:23 PM
    Are proguard rules really needed if you use
    Type.serializer()
    on Jvm/Android? In what cases would a reflective serializer be used then?
    j
    • 2
    • 10
  • i

    ivan.savytskyi

    09/17/2019, 6:31 PM
    hey folks, it might be a strange question but will shoot anyway. https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/examples.md#supported-properties
    Initializers are called iff (if and only if) property is @Transient or optional and was not read (see below).
    Is there any way to change this default behaviour
    if was not read
    , make initializer to be called without check if it was seen or not? (Basically have computed properties that only been serialized but never deserialized)
    n
    • 2
    • 5
  • h

    Hamed Ghasemzadeh

    09/19/2019, 2:20 PM
    this is the package.json for “kotlin/kotlinx-serialization-kotlinx-serialization-runtime.js” v0.12.0, “kotlin-test-nodejs-runner” are not found in npm public repo. We are depending to kotlinx-serialization in our js target, should we maintain “kotlin-test-nodejs-runner” in our own internal repo? or?
    Untitled
    s
    • 2
    • 1
  • j

    Justin

    09/19/2019, 4:47 PM
    I recently experienced a crash on iOS with the following message:
    Instances of kotlin.Error, kotlin.RuntimeException and subclasses aren't propagated from Kotlin to Objective-C/Swift.
    
    Other exceptions can be propagated as NSError if method has or inherits @Throws annotation.
    
    Uncaught Kotlin exception: kotlinx.serialization.MissingFieldExcpetion: Field 'deviceId' is required, but it was missing
    As the message suggests, the KMP library failed to deserialize to:
    @Serializable data class Details(val id: String, val deviceId: String)
    ...because the JSON string didn't contain a
    deviceId
    field, hence the crash on the iOS app using the library. I have already fixed this specific crash by modifying the model as follows:
    @Serializable data class Details(val id: String, val deviceId: String? = null)
    But my question is this: Is there a way to have
    kotlinx.serialization
    propagate any/all exceptions it throws to the implementing platform (iOS/Android/Web/etc.) to decide how to handle it? In this case, it would have been preferable to have caught this error in iOS, logged it using the iOS logging service, and not-crashed. Any ideas would be much appreciated, thanks!
    s
    s
    • 3
    • 2
  • n

    Nikky

    09/22/2019, 7:56 PM
    does anyone have a working example of how to serialize sealed classes? for me i just get empty json objects when i use
    BaseClass.serializer()
    d
    • 2
    • 10
  • j

    Justin

    09/25/2019, 3:06 PM
    Say you have JSON with a field that contains a
    List<Any?>
    . In practice, the
    Any?
    can be (a)
    null
    , (b) a
    String
    , (c) an
    Int
    , or (d) another `List<Any?>. What's the best practice for deserializing this with
    kotlinx.serialization
    ? Currently, I'm doing
    @ContextualSerialization
    like this:
    @Serializable
    data class Items(
        val id: Int,
        val values: List<@ContextualSerialization Any?> = emptyList()
    )
    This seems like the right direction, except I'm not sure how to get from this to an array of usable types (e.g. String, Int, List<Any>)?
    d
    • 2
    • 17
  • b

    basher

    09/25/2019, 5:48 PM
    Is it possible to add extension functions to a class that is serializable? I've been able to add them to
    KSerializer<T>
    , but I'd prefer to add an extension function to
    T
    , for example
    c
    • 2
    • 5
  • k

    Kroppeb

    09/26/2019, 4:42 PM
    Say I have the following class structure and desired way to serialise/deserialise them, can and how would I make serialiser for them
    Untitled
    s
    • 2
    • 1
  • r

    robgray

    09/26/2019, 8:13 PM
    I'm seeing some weird bug using `Mapper.notNullable()` with int backed enums. When I map this object I am there is no `enumListProp` key in the map it returns
    • 1
    • 2
  • b

    basher

    09/26/2019, 10:43 PM
    Is it possible to make the fact that a class is
    @Serializable
    internal
    ? I want to expose a class publicly, but I don't to provide access to its serializer
    d
    • 2
    • 2
  • b

    Big Chungus

    09/27/2019, 8:57 AM
    Is there a way to serialize KClass? Or at least construct KClass from qualified name
    s
    • 2
    • 1
  • k

    Kroppeb

    09/27/2019, 12:33 PM
    I have the following class strucutre:
    @Serializable
    @Polymorphic
    sealed class Command {
    	companion object { val context = SerializersModule {
    		polymorphic(CommandTest::class) {
    			addSubclass(Function.serializer())
    			addSubclass(Foo.serializer())
    		}
    		include(Foo.context)
    	}}
    
    	@Serializable
    	@SerialName("function")
    	class Function(val name:String): Command()
    
    	@Serializable
    	@SerialName("foo")
    	@Polymorphic
    	sealed class Foo : Command(){
    		companion object { val context = SerializersModule {
    			polymorphic(Foo::class) {
    				addSubclass(FooBar.serializer())
    			}
    		}}
    
    		@Serializable
    		@SerialName("foobar")
    		class FooBar(val x:Int, val y: Int, val z: Int): Foo()
    	}
    }
    And I have a reader that reads each time to the next space. I want
    FooBar
    to be serialised and deserialised by
    foo foobar
    but if i try deserialised it says
    foo
    isn't registered and I get a NPE when serialising. Is there a way to do this?
    d
    • 2
    • 11
Powered by Linen
Title
k

Kroppeb

09/27/2019, 12:33 PM
I have the following class strucutre:
@Serializable
@Polymorphic
sealed class Command {
	companion object { val context = SerializersModule {
		polymorphic(CommandTest::class) {
			addSubclass(Function.serializer())
			addSubclass(Foo.serializer())
		}
		include(Foo.context)
	}}

	@Serializable
	@SerialName("function")
	class Function(val name:String): Command()

	@Serializable
	@SerialName("foo")
	@Polymorphic
	sealed class Foo : Command(){
		companion object { val context = SerializersModule {
			polymorphic(Foo::class) {
				addSubclass(FooBar.serializer())
			}
		}}

		@Serializable
		@SerialName("foobar")
		class FooBar(val x:Int, val y: Int, val z: Int): Foo()
	}
}
And I have a reader that reads each time to the next space. I want
FooBar
to be serialised and deserialised by
foo foobar
but if i try deserialised it says
foo
isn't registered and I get a NPE when serialising. Is there a way to do this?
d

Dominaezzz

09/27/2019, 12:58 PM
Where have you registered it?
k

Kroppeb

09/27/2019, 12:59 PM
What do you mean?
d

Dominaezzz

09/27/2019, 1:00 PM
How do you serialize?
Json.stringify
?
k

Kroppeb

09/27/2019, 1:01 PM
No a custom encoder / decoder build on
ElementValueEncoder
and
ElementValueDecoder
To simplify it reads a string and splits it on the spaces
d

Dominaezzz

09/27/2019, 1:03 PM
Ah I see.
k

Kroppeb

09/27/2019, 1:03 PM
The problem is that to deserialise
foo foobar
it would need to read 2 strings. But I can't do that without coding it into the reader.
d

Dominaezzz

09/27/2019, 1:03 PM
Polymorphism is not sup..... exactly!
That's how it's done in the Json one.
k

Kroppeb

09/27/2019, 1:04 PM
?
d

Dominaezzz

09/27/2019, 1:05 PM
https://github.com/Kotlin/kotlinx.serialization/blob/a45e71af8bff3f76a3774fd0f8a1425de800a847/runtime/commonMain/src/kotlinx/serialization/json/internal/Polymorphic.kt
View count: 3