https://kotlinlang.org logo
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
benchmarks
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
confetti
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
lincheck
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
Title
w

why

04/21/2023, 10:23 AM
[Not solved] is it possible to have multiple SerialName for a single class?
@Serializable
@SerialName("video")
data class Video(
  val title: String,
  val videoId: String,
...
) : Result
j

Javier

04/21/2023, 10:25 AM
@JsonNames(...)
w

why

04/21/2023, 10:26 AM
This annotation is not applicable to target 'class'.
j

Javier

04/21/2023, 10:26 AM
tbh I haven't used
@SerialName
over classes, only over properties
I don't even know it was possible, and I am not sure what happens if on the field is used a different name than over the class. Probably it is not a good pattern with combined the class with networking
w

why

04/21/2023, 10:29 AM
can you expand on combined the class with networking?
j

Javier

04/21/2023, 10:59 AM
a class can be shared with multiple endpoints, which can be using a different name per endpoint. If you put the SerialName on each field, you are good. The use case of having multiple names in the same endpoint is an IMO, bad backend implementation so you have to workaround it with JsonNames, but you have no choice, for the other part you have the choice to use field over class
w

why

04/21/2023, 11:26 AM
To give more context, I'm doing polymorphic deserialization that's what @SerialName on a class is good for. Also, I'm not doing backend, I only consume a third party RESTapi. I'm on Android
Having a different Video class for each endpoint JSON that has different 'type' field IMO is outrageous
j

Javier

04/21/2023, 11:29 AM
I was talking from the client perspective, no backend
w

why

04/21/2023, 11:31 AM
JsonNames are no good for this usecase
the endpoint returns mixed data not the typical Products, Users scenario (noSQL?)
But thanks for your input.
j

Javier

04/21/2023, 11:37 AM
I didn't talk about having two different classes, but using SerialName over the class instead of over the field
w

why

04/21/2023, 11:40 AM
Then I don't follow what you're trying to say. Having @SerialName("video") over the class Is my problem. Having @SerialName("video", "shortVideo", "longVideo", ...) would solve my problem.
j

Javier

04/21/2023, 11:41 AM
don’t use SerialName over the class and your problem is gone
w

why

04/21/2023, 11:43 AM
then how do you deserialize a mixed data endpoint with the 'type' field in every item in that json list?
j

Javier

04/21/2023, 11:56 AM
If I have understood correctly, something like this?
data class Response(@JsonNames("foo", "bar") val fooBar: FooBar)

sealed class FooBar {
  data class Foo(val foo: Foo) : FooBar()
  data class Bar(val bar: Bar) : FooBar()
}
With the json response/s maybe I can help more
as my previous answer, in my mind, would be better so
data class Response(@SerialName("foo") val foo: FooBar, @SerialName "bar") val bar: FooBar)

// or even
data class Response(@SerialName("foo") val foo: Foo, @SerialName("bar") val bar: Bar)

sealed class FooBar {
  data class Foo(val foo: Foo) : FooBar()
  data class Bar(val bar: Bar) : FooBar()
}
So I can be missing something
w

why

04/21/2023, 12:08 PM
/*
[
  {
    type: "type1",
    title: String,
    ...
  },
  {
    type: "type2",
    title: String,
    ...
  },
  {
    type: "type3",
    title: String,
    ...
  }
]
 */
this is the JSON response
the potential problem is when you have for example type1 and type 2 having the common fields in a class because they are the same entity (say User), but some times you don't need age or weight or...
j

Javier

04/21/2023, 12:12 PM
That could be enough:
sealed class Foo {
    data class(val type: Type1, val title: String, ...) : Foo()
    data class(val type: Type2, val title: String, ...) : Foo()
    data class(val type: Type3, val title: String, ...) : Foo()
}
But probably you can extract common fields:
sealed class Foo<T> {
    abstract val type: T
    abstract val title: String
    ...
}
if the field
type
is changing the name, then:
sealed class Foo {
    data class(val type1: Type1, val title: String, ...) : Foo()
    data class(val type2: Type2, val title: String, ...) : Foo()
    data class(val type3: Type3, val title: String, ...) : Foo()
}
w

why

04/21/2023, 12:14 PM
so that's a lot of code, do yo agree?
if @SerialName("type1") takes multiple values, I can make one class with all the possible fields but nullable
j

Javier

04/21/2023, 12:16 PM
You can't avoid it I think
w

why

04/21/2023, 12:16 PM
we can if we have @SerialName("t1", "t2", ...)
j

Javier

04/21/2023, 12:17 PM
let me think
w

why

04/21/2023, 12:17 PM
ok take your time + thanks for you efforts
j

Javier

04/21/2023, 12:19 PM
you need to change the structure and maybe you can get less code maybe something so:
val list: List<Foo> // backend response

data class Foo(
    @JsonNames("type1", "type2", ...) val type: Type,
    val title: String,
    ...
)

sealed class Type {
    data class Type1(...) : Type()
    data class Type1(...) : Type()
    ...
}
w

why

04/21/2023, 12:23 PM
it doesn't really solve the fact that I need to have multiple classes for the same thing aka multiple crazy names. If im gonna have that, I think I rather have @SerialName("type1") class Type1, @SerialName("type2") class Type2 ..
with no inheritance no crazy generics, just plain data classes, but it's still lot of code for one thing
a

Adam S

04/24/2023, 12:08 PM
the SerialName isn’t really used in JSON edit for classes, because JSON objects don’t have a name. Compare with something like XML, where the tag is kind of equivalent to the SerialName. SerialName is important to KxS internal functioning though, and it should be distinct. Why do you want to have multiple serial names though? The JSON you provided can be parsed by a single class
j

Javier

04/24/2023, 2:59 PM
@SerialName
is used on fields, over classes I haven't tried
a

Adam S

04/24/2023, 3:01 PM
oops, you’re right, I meant on classes.
@SerialName
is used for JSON properties, and also to determine the
type
field for polymorphic objects.
w

why

05/03/2023, 3:46 PM
@Adam S I don't know if you understood what my problem was. TL;DR I want this @SerialName("t1", "t2", ...) over classes not properties, maybe that would be a good feature to add to the lib, but the thing is people are so used to just creating new classes and call it decoupling or whatever, maybe that's why it is not requested nor implemented. Thanks for ur input.
a

Adam S

05/03/2023, 3:52 PM
yeah, maybe I didn’t understand :) for the example you gave,
@Serializable
@SerialName("video")
data class Video(
  val title: String,
  val videoId: String,
) : Result
if I use this to serialize some data
fun main() {
  val video = Video(title = "Star Wars", videoId = "001011101")

  println(Json.encodeToString(video))
}
I’d end up with
{
  "title": "Star Wars",
  "videoId": "001011101"
}
and there’s no reference to
@SerialName("video")
, because JSON objects don’t have names. Where should the
@SerialName("video")
be used? Where should it go in the JSON?
w

why

05/03/2023, 3:54 PM
you need to look at the json I provided to see the full picture
/*
[
  {
    type: "type1",
    title: String,
    ...
  },
  {
    type: "type2",
    title: String,
    ...
  },
  {
    type: "type3",
    title: String,
    ...
  }
]
 */
when I first asked i didn't provide it because i assumed it's clear since I used SerialName on the class but ok.
so "type1" would be "video" for example etc..
a

Adam S

05/03/2023, 4:04 PM
I saw the JSON, but it doesn’t help me understand, because it’s got different fields names to the Kotlin data class you shared, and it’s not valid JSON, and it doesn’t need to be polymorphic https://kotlinlang.slack.com/files/U01681FLZC2/F0546H08TCP/sample.kt.cpp
can you share the complete JSON data you’re trying to parse?