https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

dMusicb

05/04/2022, 7:19 PM
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

Landry Norris

05/04/2022, 7:29 PM
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

dMusicb

05/04/2022, 7:45 PM
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

Landry Norris

05/04/2022, 7:54 PM
You can. When you build the Json object, you can configure the discriminator name.
👍 1
d

dMusicb

05/04/2022, 10:53 PM
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

Landry Norris

05/04/2022, 10:57 PM
I don't think so, but you could catch and log the SerializationException.
d

dMusicb

05/04/2022, 11:01 PM
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

Landry Norris

05/04/2022, 11:03 PM
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

Paul Griffith

05/04/2022, 11:21 PM
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

dMusicb

05/04/2022, 11:32 PM
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.
2 Views