Good morning, we have a json with a field `type` ,...
# serialization
d
Good morning, we have a json with a field
type
, we implemented the model with `sealed class`; serialization works flawlessly, but deserialization doesn’t include the field
type
. What is the best way to deal with it? We’re on 1.4.10
i
They type of the variable needs to be the parent sealed class.
Copy code
sealed class Response {
class Success() : Response()
}

val r: Response = Success(data)
val jsonString = Json.encode(r)

val r: Response = Json.decode("json with type")
d
For what my coworker told me, when doin
Json.encode(myClass)
, the
type
field is skipped ( not in the generated String )
Might be relevant; I can't tell if you're deserializing data that you're generating or that's coming from elsewhere
i
It is skipped if the type of the variable is the implementation class itself. So in the example above, if I replace
val r: Response
with
val r: Success
json will not add the
type
field. Idk if that's how it supposed to work or it's a bug. with
val r: Response
you get
{ type: Success, data: int}
with
val r: Success
you get
{ data: int}
With the classDiscrimantor, you can change the
type
key to be anything, instead of
type
it can be
pet
and
{pet: Dog, data: name}
p
Yeah, that's the behavior I was seeing that led me to that issue. I worked around it with a custom serializer for the inner class that delegates to the parent class' serializer, but that's not ideal
d
Thank you for the answers