Skip to content

Instantly share code, notes, and snippets.

@patjackson52
Created March 6, 2019 18:15
Show Gist options
  • Select an option

  • Save patjackson52/367fc3f7c72d61ce0dbc34399c8f683d to your computer and use it in GitHub Desktop.

Select an option

Save patjackson52/367fc3f7c72d61ce0dbc34399c8f683d to your computer and use it in GitHub Desktop.
Polymorphic JSON parsing with Kotlinx Serialization
val response: MyFoodWrapper = client.get {
apiUrl("url_to_polymorphic_json")
}
@Serializable
class MyFoodWrapper(
val items: Map<String, Food>
) {
@Serializer(Feed::class)
companion object : KSerializer<Feed> {
override val descriptor: SerialDescriptor = object : SerialClassDescImpl("Feed") {
init {
//anything needed here? how to add element when dealing with dynamic field names?
}
}
override fun serialize(output: Encoder, obj: Feed) {
TODO("Not implemented")
}
override fun deserialize(input: Decoder): Feed {
val inp = input.beginStructure(descriptor)
val keyName = inp.decodeStringElement(descriptor, 0)
//keyName will have value 'dynamicName1'
//How to get the object for keyname?
}
{
"dynamicName1": {
"type": "pizza",
"data": {
//pizza object
}
},
"dynamicName2": {
"type": "hoagie",
"data": {
//hoagie object
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment