Is it possible to choose a `Serializer` to handle a `JsonObject` ? I would like to achieve `String`...
d
Is it possible to choose a
Serializer
to handle a
JsonObject
? I would like to achieve
String
->
JsonObject
-> Logic with
when
statement ->
*MyChosenClass*
. Thank you.
j
What type is the property in your model?
MyChosenClass
? or
JsonObject
? It sounds like you're describing a normal delegating
KSerializer<MyChosenClass>
where the delegate is
JsonObject.serializer()
d
MyChosenClass
is the property I'm trying to get to after evaluating a
typeId
from its wrapper class. So
Copy code
@Serializable(WrapperSerializer::class)
data class Wrapper(
    val typeId: Long,
    val myChosenClass: MyChosenClass,
)
The logic I mentioned is occurring inside the
WrapperSerializer
. I can get the
JsonObject
just fine, it's just after I've identified which serializer to use, I'm not sure how to apply it to a
JsonObject
a
d
Maybe, I'm looking into that right now and have used it before, but maybe I just need to readjust my thinking. As for what the path I was going down, I was trying to achieve this inside the serializer.
Copy code
when(typeId) {
    1 -> Wrapper(typeId = typeId, myChosenClass = decoder.decode(MyChosenClass.Subclass1.serializer(jsonObject)))
}
j
You don't want to use the
Decoder
because you're not reading from the original JSON but from a model object
You want like
json.decodeFromJsonElement(serializer, jsonObject)
that is saying, use the same
json
format as the source, use the chosen
serializer
of the chosen subclass, and use
jsonObject
as the model from which to bind properties. There's no actual serialized JSON decoding happening here.
d
I think I see what you're saying. Will I have to manually bind the properties from
jsonObject
into my chosen subclass though? I was trying to avoid that since there's quite a few subclasses and I just wanted to select the serializer from the
typeId
.
j
That call will give you back an instance of your chosen subclass
d
Gotcha, I was able to get this moving. Thanks a ton to both of you