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
l

ludwig

06/15/2018, 10:33 AM
@nikolay Yes, sorry, that is correct, it was a typo in the example
n

nikolay

06/15/2018, 10:40 AM
have you tried to debug? where it gets stuck?
l

ludwig

06/15/2018, 10:48 AM
Yes, it keeps thinking that it needs to parse toJson whenever it reaches the layer
So it gets stuck in a recursion
n

nikolay

06/15/2018, 12:25 PM
btw, why here
(var type: TypeEnum, var layer: Layer)
you have
var
? maybe it should be
val
?
l

ludwig

06/15/2018, 12:44 PM
I’ve tried that too, it doesn’t matter unfortunately
n

nikolay

06/15/2018, 1:32 PM
have you tried without
toJson
as was suggested? tbh not sure if it would work, because I’ve though that they are both mandatory
l

ludwig

06/15/2018, 1:36 PM
it is mandatory, so I can’t try it
n

nikolay

06/15/2018, 1:40 PM
maybe you could post JSON that you trying to parse ?
I’m really curious about issue, because I’m currently migrating to Moshi
l

ludwig

06/15/2018, 1:43 PM
I can’t post the exact one, but it has the exact same structure as the example
n

nikolay

06/15/2018, 1:47 PM
okey
l

ludwig

06/15/2018, 1:49 PM
Other than this issue, Moshi is great, so don’t be discouraged 🙂
n

nikolay

06/15/2018, 2:04 PM
Why have I asked about JSON, because I have one idea. Point is that I could not imagine what is coming in JSON under name
layer
. Because from Response class I see that your JSON supposed to have 2 fields. Something like:
{
    "type": "X" (or "Y"),
    "layer": ..... (not clear)
}
My suggestion would be to have another class, let’s say
ResponseRaw
which would be exactly like your JSON (and it should not include
Layer
in the structure). Something like:
{
    "type": "X" (or "Y"),
    "something": {
        "variable1": 1,
        "variable2": 2
    }
}

data class ResponseRaw(val type: TypeEnum, val something: Something)
And then your adapter would looks differently:
class LayerAdapter {
    @FromJson
    fun fromJson(response: ResponseRaw) : Layer = when(response.type) {
        Y -> YLayer()
        X -> XLayer()
   }

    @ToJson
    fun toJson(layer: Layer) : ResponseRaw = when(layer) {
        is YLayer -> ResponseRaw(Y, layer.toSomething())
        is XLayer -> ResponseRaw(X, layer.toSomething())
    }
}
I hope you get what I mean 🙂
l

ludwig

06/15/2018, 2:08 PM
Thank you very much for the effort, and you’re correct, that works, and that’s an implementation that I can’t use, because we are using this format in almost every request, and some of these “layers”, have up to 30 different cases, so it would be a huge mess when dealing with it, hence why I want it to be explicit types that are being parsed directly 🙂
n

nikolay

06/15/2018, 2:09 PM
but I think Moshi simply could not parse your JSON to
Layer
, because it doesn’t know which one to pick
l

ludwig

06/15/2018, 2:10 PM
But isn’t that what I’m trying to tell Moshi? What to parse that is
n

nikolay

06/15/2018, 2:10 PM
nope
how should it distinguish which
Layer
to take?
l

ludwig

06/15/2018, 2:11 PM
What is the when(layer) { is YLayer -> etc } for then?
n

nikolay

06/15/2018, 2:12 PM
you should probably write more low level adapter, that operates with strings
class StageAdapter {
  @FromJson fun fromJson(jsonReader: JsonReader, delegate: JsonAdapter<Stage>): Stage? {
    val value = jsonReader.nextString()
    return if (value.startsWith("in-progress")) Stage.IN_PROGRESS else delegate.fromJsonValue(value)
  }
}
but you have
class Response(var type: TypeEnum, var layer: Layer)
how would it parse Layer here?
l

ludwig

06/15/2018, 2:14 PM
Response = when(layer) { is YLayer -> Response(Y, layer)} - I’m creating a new Response, with the specified layer?
Response = when(layer) { is YLayer -> Response(Y, YLayer() )
Isnt that parsing the correct layer?
n

nikolay

06/15/2018, 2:15 PM
no, it is already taking
Response
as param
pass
jsonReader: JsonReader, delegate: JsonAdapter<Stage>
there
or something
l

ludwig

06/15/2018, 2:15 PM
I’m talking about toJson btw
is it you? 🙂
l

ludwig

06/15/2018, 2:19 PM
Nope, just used the Layer as an example 🙂
n

nikolay

06/15/2018, 2:19 PM
class LayerAdapter {
    @FromJson
    fun fromJson(layerJson: LayerJson): Layer = when (layerJson.layerType) {
        LayerType.SHAPE -> ShapeLayer(layerJson.layerType, layerJson.shape ?: "")
        LayerType.TEXT -> TextLayer(layerJson.layerType, layerJson.text ?: "")
        LayerType.IMAGE -> ImageLayer(layerJson.layerType, layerJson.image ?: "")
    }

    @ToJson
    fun toJson(layer: Layer): LayerJson = when (layer) {
        is ShapeLayer -> LayerJson(layer.type, shape = layer.shape)
        is TextLayer -> LayerJson(layer.type, text = layer.text)
        is ImageLayer -> LayerJson(layer.type, image = layer.image)
        else -> throw RuntimeException("Not support data type")
    }
}
that’s more or less what I’m trying to say
l

ludwig

06/15/2018, 2:20 PM
Yes, and I can’t be using that, because we are re-using the Layer type everywhere, which will then in some cases have 30 optional parameters as they have defined in that example
I’m trying to go one step further, and not have that, instead parse them out directly
n

nikolay

06/15/2018, 2:21 PM
Let’s say we have two JSONs
{
  "type": "X",
  "layer": {
    "type": "LayerX",
    "prop": 42
  }
}
and
{
  "type": "X",
  "layer": {
    "type": "LayerY",
    "prop": 100
  }
}
How Moshi could understand how to parse it to your
Response
class?
l

ludwig

06/15/2018, 2:23 PM
@ToJson fun toJson(layer: Layer) : Response = when(layer) { is YLayer -> Response(Y, LayerY(prop = layer.prop)) is XLayer -> Response(X, LayerX(prop = layer.prop)) } Because the sealed class’s has different fields on them
n

nikolay

06/15/2018, 2:23 PM
man, it takes as param
Layer
!!
🙂
but
"layer": {
        "type": "LayerY",
        "prop": 100
    }
could not be parsed to
Layer
and I’m talking about
fromJson
l

ludwig

06/15/2018, 2:24 PM
And I’m talking about the toJson!
sealed class Layer() class YLayer(type: String, prop: Int) : Layer And now it can be parsed
n

nikolay

06/15/2018, 2:26 PM
no, it can’t, I think
l

ludwig

06/15/2018, 2:26 PM
The parsing works, believe it or not, because I get the object when I’m doing it like this, the only thing that isn’t working as expected, is when it’s done, it starts to nest the layer
n

nikolay

06/15/2018, 2:26 PM
anyway, I think either I don’t understand the problem or I could not explain what I mean 🙂
l

ludwig

06/15/2018, 2:27 PM
The actual parsing from toJson and fromJson works when you run it once, then I get the real objects, depending on what type of Layer I send in, or what Response is coming out. It’s when it’s done parsing, it starts to parse it again, and again 🙂
Run it once using the debugger of course
n

nikolay

06/15/2018, 2:29 PM
then I really don’t get your issue, sorry man!
l

ludwig

06/15/2018, 2:29 PM
Thanks for trying to help!