https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
serialization
  • d

    dimitar_

    06/14/2021, 6:59 PM
    Hi people 🙂 I wrote a serialization implementation that uses Amazon’s Ion to [de]serialize to binary. It stores just flat data, and relies on Kotlin’s Serialization framework for the objects’ structure. Also, the implementation retains the object references upon deserialization. It’s a really simple implementation and I would like to hear your opinion. I just started with it - and plan to develop it further and maintain it. I wrote some simple tests for some cases I can think of, and everything seems to be working ok. https://github.com/dimitark/kotlinx-serialization-ion
    d
    • 2
    • 4
  • m

    MBegemot

    06/15/2021, 4:40 PM
    After updating to latest ver, I have huge problems with proguard ClassCastException and class cannot be cast to reflect.parametrized tipe, I have the feeling that it's more a ktor issue but not sure, debuging this kind of stuff its kind a hell ... specially taking in account that everything went smooth before the update
    • 1
    • 1
  • d

    dimitar_

    06/16/2021, 3:00 PM
    Hey, I'm trying to serialize an object, that has an array of LongRange objects - but with no luck. I have a custom serializer for the LongRange objects
    object LongRangeSerializer: KSerializer<LongRange> {
        override val descriptor = buildClassSerialDescriptor("LongRange") {
            element<Long>("first")
            element<Long>("last")
        }
    
        override fun deserialize(decoder: Decoder): LongRange {
            var first = 0L
            var last = 0L
    
            decoder.decodeStructure(descriptor) {
                first = decodeLongElement(descriptor, 0)
                last = decodeLongElement(descriptor, 1)
            }
    
            return first..last
        }
    
        override fun serialize(encoder: Encoder, value: LongRange) {
            encoder.encodeStructure(descriptor) {
                encodeLongElement(descriptor, 0, value.first)
                encodeLongElement(descriptor, 1, value.last)
            }
        }
    }
    And I tried:
    @Serializable class Container(@Serializable(with = LongRangeSerializer::class) val ranges: Array<LongRange>)
    with no luck. Can't seem to find any pointers anywhere. Tried using a List also, tried also with
    @Contextual
    - same issue. The error is:
    Kotlin: Serializer has not been found for type 'LongRange'. To use context serializer as fallback, explicitly annotate type or property with @Contextual
    d
    e
    • 3
    • 6
  • m

    marzelwidmer

    06/16/2021, 5:36 PM
    Hello I try to migrate Jackson to serializer… how I work with dates ? my Jackson JSON format looks like :
    @JsonFormat(pattern = "yyyy-MM-dd")
    j
    • 2
    • 5
  • m

    Matthew Cachia

    06/17/2021, 11:54 AM
    Hi guys, does kotlinx.serialization supports Json References? I'm having a hard time finding a definitive answer. Much appreciated.
    d
    n
    • 3
    • 4
  • s

    sendoav

    06/18/2021, 8:32 AM
    Hi all, I am deserializing a big json structure and one of the child object is throwing a JsonDecodingException, thus the serialization process is not returning anything. Is it possible to configure kotlin serialization to continue the serialization process even if one of the child objects is erroneous?
    d
    b
    • 3
    • 5
  • n

    Nick

    06/18/2021, 7:32 PM
    Why am I getting this error?
    kotlinx.serialization.SerializationException: Serializer for class 'Pagination' is not found.
    My data class:
    import kotlinx.serialization.Serializable
    
    @Serializable
    data class Pagination<T>(
        val count: Int,
        val next: String? = null,
        val previous: String? = null,
        val results: List<T>
    )
    Build.gradle:
    plugins {
        id("com.android.application")
        kotlin("android")
        id("kotlin-android-extensions")
        kotlin("plugin.serialization") version Versions.kotlin
    }
    • 1
    • 2
  • r

    Rainer Schlonvoigt

    06/21/2021, 2:33 PM
    Probably a stupid question, but googling doesn’t get me anywhere 😕 Can i easily use
    @Serializable(with=...)
    on a Set of a custom class? More specifically, my scenario looks like this:
    @Serializable
    data class MyClass(
        @Serializable(with=???)
        val mySet: Set<UUID>
    )
    where UUID is from java.util so i can’t annotate it
    d
    e
    • 3
    • 6
  • j

    jeggy

    06/21/2021, 6:56 PM
    I'm wondering what's the thoughts about making a Kotlin Library which uses the kotlin serialization compiler plugin? Or should I try to avoid using
    @Serializable
    for libraries?
    d
    d
    r
    • 4
    • 5
  • c

    christophsturm

    06/22/2021, 8:09 AM
    is there a utility method that converts json to a Map<String, Any>, or do I have to serialize to a map<String, JsonElement> and then do something like this?
    it.mapValues { (_, value) ->
                    when (value) {
                        is JsonPrimitive -> value.content
                        JsonNull -> null
                        is JsonObject -> TODO()
                        is JsonArray -> value.map { it.jsonPrimitive.content }
                    }
                }
    d
    • 2
    • 2
  • s

    spierce7

    06/24/2021, 1:41 PM
    Does kotlin serialization support the new sealed interfaces?
    s
    c
    • 3
    • 2
  • m

    Mustafa Ozhan

    06/25/2021, 3:43 PM
    I have this jvmJar task to build a jar for my backend
    val jvmJar by tasks.getting(Jar::class) {
        doFirst {
            manifest {
                attributes["Main-Class"] = "${ProjectSettings.packageName}.backend.BackendAppKt"
                from(
                    configurations
                        .getByName("runtimeClasspath")
                        .map { if (it.isDirectory) it else zipTree(it) }
                )
            }
        }
    }
    this task is failing now with this error
    > Task :backend:jvmJar FAILED
    
    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Execution failed for task ':backend:jvmJar'.
    > Cannot convert the provided notation to a File or URI: ZIP '/Users/mustafa.ozhan/.gradle/caches/modules-2/files-2.1/io.ktor/ktor-serialization/1.6.0/8377a04c8a0e11d31ef17f1c0c06bda6c7b2fdc4/ktor-serialization-jvm-1.6.0.jar'.
      The following types/formats are supported:
        - A String or CharSequence path, for example 'src/main/java' or '/usr/include'.
        - A String or CharSequence URI, for example 'file:/usr/include'.
        - A File instance.
        - A Path instance.
        - A Directory instance.
        - A RegularFile instance.
        - A URI or URL instance.
        - A TextResource instance.
    any idea how we can fix that ?
    n
    • 2
    • 2
  • r

    Rohen Giralt

    06/29/2021, 2:28 PM
    Hey everybody! Does anybody know if it’s possible to register for serialization (but not deserizalization) an interface? My use case is in a webserver; I want to be able to convert any class that implements some interface into JSON to return to a GET request. I was able to write a custom serializer for the interface fairly easily, but the issue comes in using it; I can do
    val json = Json {
        contextual(MyInterface::class, MyInterfaceSerializer)
    }
    but since that works on the KClass of the underlying type, I get an
    kotlinx.serialization.SerializationException: Serializer for class 'MyInterfaceImpl' is not found.
    I could use the
    encodeToString
    method explicitly, rather than using contextual serialization, but since I’m using Ktor’s ContentNegotiation feature, I wouldn’t be able to retain any of its features (such as a correct Content-Type header, etc.) without a bunch more work. Finally, I could also register each subtype polymorphically, but that seems like • a lot of repeated code (since all serializers would be the same) • a little bit of a breach of encapsulation (I’d like to have the serializer in a separate module, since the interface and its implementations don’t need to know about how they’re being displayed to the user, and vice versa) Any ideas?
    d
    r
    • 3
    • 12
  • l

    Lilly

    06/29/2021, 10:19 PM
    Hi, I want to filter data that comes from a bluetooth device. The data I get from this device is a bunch of "Parameter", so after parsing this data I have a list of sth like this: { key: "Parameter1", data: { <a bunch of bytes> } The amount of "Parameter" is at least 100. The problem I have is that I need to group these 100 "Parameter" by specific criteria for my UI. For example 30 "Parameter" are of type "Status", but I don't have the information which Parameter is of which type. My old approach uses a List with the possible "Status" "Parameter" and while iterating over the whole "Parameter" list, I do the filtering. I have multiple such groups. I'm looking for a solution where I have just one big table where I can query from, e.g. "get all Pareameter of type Status". My initial idea was a database but this might be overpowered. So my second idea is to use a json file and perform some filter when deserialize. Can you guys give me an advice, how to solve this properly? When you think, JSON is suffiecient for this, can the serialization lib perform filtering on deserialization? EDIT: tl;tr: I get uncomplete data from a remote device but want to reorganize (filter/group) this data by specific missing criteria that I don't have and that I need to grab from a database or a file
    n
    • 2
    • 2
  • i

    itnoles

    06/30/2021, 2:06 AM
    Is there is known issues for js(IR) is not working for kotlinx serialization?
    a
    b
    • 3
    • 2
  • p

    Philip S

    06/30/2021, 9:02 AM
    I'm trying to convert a piece of Moshi code in a JsonAdapter to a equivalent KSerializer without success. Code in thread 🧵
    e
    • 2
    • 2
  • w

    Waqas Tahir

    07/01/2021, 2:20 PM
    Hi Everyone ! Let's say I have a class that extends List class , and I am using it as a property in another class that I want to serialize , How can I write serializer , I just want to cast that property to a List and then serialize and deserialize as a List , does anyone reply here ?
    b
    • 2
    • 8
  • w

    Waqas Tahir

    07/02/2021, 1:24 AM
    Getting this error Everywhere I specified a custom serializer using @Serializable(with = SomeSerializer::class)
    r
    d
    j
    • 4
    • 8
  • y

    Yuri Drigin

    07/06/2021, 12:39 PM
    Hi folks. I need to use generic serialisation class, but got compiler error:
    Caused by: java.lang.AssertionError: Couldn't load KotlinClass
    @Serializable
    data class SocketMessage<T>(
        val timestamp: Long?,
        val message: T
    )
    How can I fix it? kkotlinx-serialization 1.2.1 Thanks
    e
    • 2
    • 1
  • b

    benkuly

    07/07/2021, 10:54 AM
    Is it possible, that
    @Contextual
    does not work with IR compiler and generic classes or do I something wrong? Here is a minmal example: https://gitlab.com/benkuly/trixnity/-/blob/ir-compiler-issues/trixnity-core/src/co[…]in/kotlin/net/folivo/trixnity/core/model/events/UnsignedData.kt
    e
    d
    • 3
    • 11
  • j

    Jason Ankers

    07/08/2021, 4:03 AM
    With kotlinx-serialization, I want to be able to annotate a property as
    @Ref
    and have the serializer only serialize the
    id
    property of the referenced type. Is this possible? I.e.
    data class Video(
        val name: String,
        @Ref val user: User,
    )
    
    // serialized to:
    
    {
        name: "example",
        user: {
            id: "123"
        }
    }
    e
    d
    • 3
    • 3
  • m

    Mark Allanson

    07/08/2021, 2:40 PM
    For polymorphic objects, Is there any way of suppressing the type field output into json by
    kotlinx.serialization
    when all you're doing is serializing with no care for deserialization later, or allow specification of another field instead of type as the discriminator
    e
    e
    • 3
    • 3
  • s

    snowe

    07/09/2021, 1:36 AM
    I've got the following code:
    @Serializable
    data class ChangeOrderInput(
        val oldProposal: OldProposal,
        val newProposals: List<NewProposal>
    )
    
    @Serializable
    data class OldProposal(
        val product: Product
    )
    
    @Serializable
    data class NewProposal(
        val id: String,
        val product: Product,
        val changeOrderType: ChangeOrderType? = null
    )
    
    @Serializable(with = ProductSerializer::class)
    sealed class Product {
        abstract val type: ProductType
        abstract val bundle: ProductBundle
    }
    
    object ProductSerializer : JsonContentPolymorphicSerializer<Product>(Product::class) {
        override fun selectDeserializer(element: JsonElement): DeserializationStrategy<out Product> {
            val typeString = element.jsonObject["type"]?.jsonPrimitive?.content ?: error("`type` wasn't provided for `product`")
            return when (ProductType.valueOf(typeString)) {
                ProductType.Cash -> CashProduct.serializer()
                <http://ProductType.Loan|ProductType.Loan> -> LoanProduct.serializer()
            }
        }
    }
    
    @Serializable
    data class CashProduct(
        override val type: ProductType = ProductType.Cash,
        override val bundle: ProductBundle,
        val totalPrice: BigDecimal
    ) : Product()
    
    @Serializable
    data class LoanProduct(
        override val type: ProductType = <http://ProductType.Loan|ProductType.Loan>,
        override val bundle: ProductBundle,
        val vendor: String,
        val term: BigDecimal,
        val apr: BigDecimal,
        val totalPrice: BigDecimal
    ) : Product()
    
    @Serializable
    data class ExampleResponse(
        val version: String = "",
        val outputObjects: List<NewProposal>? = listOf()
    )
    When I serialize a ChangeOrderInput object:
    val inputJsonString = input.reader().use { it.readText() }
    val request = Serialization.json.decodeFromString(ChangeOrderInput.serializer(), inputJsonString)
    val response = runBlocking {
        changeOrderWrapper.handleRequest(request)
    }
    val outputJsonString = Serialization.json.encodeToString(response)
    output.writer().use { it.write(outputJsonString) }
    it serializes both the oldProposal and newProposal correctly (see request object in the image). But when I try to deserialize the
    ExampleResponse
    object, it deserializes everything except the
    NewProposal#type
    field. I just now thought that maybe this was due to the classDiscriminator property on the Serializer, but that is not it. I tried changing it to
    #class
    and it still has the same result. Anyone know what is going on here?
    ✅ 1
    :thread-please: 1
    e
    • 2
    • 37
  • a

    akuleshov7

    07/12/2021, 10:59 AM
    ⚠️ I was suggested in #feed to publish it here also to attract more attention, if it is invalid channel - then sorry for spam: I have just released a ktoml library (0.2.6) to Maven Central. It is a fully Kotlin native serialization library for TOML configuration language. It was requested by Kotlin community, but unfortunately I am developing this alone in my free time. I would like to ask for your help in testing/contributing to this project. Or at least give it a star to make it look more attractive for new contributors. Thanks! 🙏
    👍 3
    d
    g
    • 3
    • 9
  • k

    kubele

    07/14/2021, 5:13 PM
    Hello, could anyone help with explaining why is this different?
    @Serializable
    data class Foo(
        val list: List<String> = emptyList()
    )
    val foo = Json.encodeToString(Foo())
    println(foo)
    prints
    {}
    but this implementation:
    @Serializable
    data class Foo(
        val list: List<String>
    )
    val foo = Json.encodeToString(Foo(emptyList()))
    println(foo)
    prints
    {
      "list": []
    }
    I have no idea why it’s not
    {
      "list": []
    }
    in both cases
    j
    • 2
    • 3
  • p

    Phạm Minh Tuấn

    07/15/2021, 2:32 AM
    Hi everyone, i face with an issue about parsing json, this is my input json
    {
      "accountNo": "",
      "address": "4",
      "amount": 1719000,
      "bankCode": "950012",
      "channel": "6015",
      "customerCode": "Evn15",
      "customerName": "EXIM",
      "localDateTime": "20210713203042",
      "providerCode": "196000",
      "senderInfo": "Evn15",
      "serviceCode": "000010",
      "sign": "",
      "trace": "000295",
      "vnpayDateTime": "20210713204024"
    }
    but when json parsed, it throw error
    Unexpected JSON token at offset 300: Expected quotation mark '\"', but had '\"' instead\nJSON input: .....gn\": \"\",\n\t\"trace\": \"000295\",\n\t\"vnpayDateTi
    that is normal json i dont know why it throw error, please help
    c
    • 2
    • 1
  • a

    altavir

    07/15/2021, 9:21 AM
    I am switching to kotlin 1.5.21 and serialization 1.2.2 and getting error:
    kotlinx.serialization.MissingFieldException: Field 'properties' is required for type with serial name 'solid.box', but it was missing.
    The
    propertiese
    field has default null value and is declared like
    public var properties: Config? = null
            protected set
    The error is thrown when trying deserialize descendant that has the default null value. Seems like a bug to me.
    p
    • 2
    • 14
  • r

    rsetkus

    07/20/2021, 4:14 PM
    Hi. Trying to deserialize cached json string to data object and getting exception:
    kotlinx.serialization.json.internal.JsonDecodingException: Expected class kotlinx.serialization.json.JsonObject (Kotlin reflection is not available) as the serialized body of kotlinx.serialization.Polymorphic<List>, but had class kotlinx.serialization.json.JsonArray (Kotlin reflection is not available)
    Json:
    [ //internal structure of json object ]
    Container data class:
    List<R>
    Function used for deserialization:
    internal inline fun <reified R : Any> String.convertToDataClass() =
        Json {
            ignoreUnknownKeys = true
        }.decodeFromString(R::class.serializer(), this)
    Code example:
    "[…]".convertToDataClass<List<SomeDataClass>()
    When going through Ktor pipeline everything works fine but it is breaking on attempt to deserialize the same response body cached as string to object. Any ideas how to fix this?
    • 1
    • 1
  • a

    ankushg

    07/21/2021, 8:42 PM
    Hey gang, I see that v1.2.2 release notes say:
    It also uses Kotlin 1.5.20 as default.
    Is there a way to ignore this "default" and use v1.2.2 with Kotlin 1.5.10? (Encountered a bug that's fixed in 1.2.2, but can't bump past 1.5.10 yet because of another issue I'm trying to chase down)
    c
    e
    • 3
    • 3
  • d

    Dario Valdespino

    07/25/2021, 8:56 PM
    Is there a way to check whether a type is serializable from inside an annotation processor? I'm writing a code generator using KSP and it would be nice to catch serialization-related problems in compile time. So far I'm able to check the type for annotations (looking for the
    @Serializable
    annotation). But what about primitives like
    Int
    and
    String
    ? Surely there must be a better way than manually keeping a list of all natively serializable types, right?
    👀 1
    s
    • 2
    • 2
Powered by Linen
Title
d

Dario Valdespino

07/25/2021, 8:56 PM
Is there a way to check whether a type is serializable from inside an annotation processor? I'm writing a code generator using KSP and it would be nice to catch serialization-related problems in compile time. So far I'm able to check the type for annotations (looking for the
@Serializable
annotation). But what about primitives like
Int
and
String
? Surely there must be a better way than manually keeping a list of all natively serializable types, right?
👀 1
s

sandwwraith

07/26/2021, 5:22 PM
welp.......... https://github.com/JetBrains/kotlin/blob/16dbafced1020ffab2542862caad8d274c07faa7/plugins/kotlin-serialization/kotlin-serialization-compiler/src/org/jetbrains/kotlinx/serialization/compiler/backend/common/TypeUtil.kt#L162
😅 1
d

Dario Valdespino

07/26/2021, 9:43 PM
Yeah, I guess i'll stick with the list then...
View count: 6