Haven't used Kotlin serialization much, what's the...
# getting-started
d
Haven't used Kotlin serialization much, what's the correct way to be able to deserialize some JSON returned by an API when it's something like:
Copy code
{
    "type": "Foo" | "Bar" | "Baz"
    "payload": FooPayload | BarPayload | BazPayload
}
l
You can use polymorphism. Make a serializable sealed class and create Foo, Bar, and Baz serializable subclasses. I would use the SerialName annotation to set the value of type it needs to match.
d
I see the @SerialName("owned") example to specify the explicit type value, is there a way to also change the "type" key itself in case the API response doesn't use type but something else like
"blahblah": "Foo" | "Bar" | "Baz"
l
You can. When you build the Json object, you can configure the discriminator name.
👍 1
d
Any idea if it's possible to utilize the ignoreUnknownKeys parameter, but potentially log warnings so they can be seen over time and fixed? i.e. we don't own the API, so we don't want our API to break when new things are added, but would like to catch it over time in the logs and update the data models.
l
I don't think so, but you could catch and log the SerializationException.
d
Hrmm so suggesting to deserialize twice, first wrapped in a try catch and if it fails w/ the serialization exception to fall back to ignoreUnknownKeys? I suppose that could work.. Would temporarily pay the cost of deserializing twice once things start to break but probably fine if fixed in time..
l
I wouldn't worry about new keys that are added, though. Your code wouldn't be able to use a key you didn't set up in the code anyways.
p
You can also use a
JsonContentPolymorphicSerializer
; you can decode the full object, do your logging, then select a (de)serializer to use based on the given key
d
Yeah I'm not worried about not utilizing the new fields, just more-so want to be able to catch schema changes from this API and update our data models accordingly so they could theoretically be utilized by someone else as needed.
Thanks Paul, will take a look at that.