Created
March 6, 2019 18:15
-
-
Save patjackson52/367fc3f7c72d61ce0dbc34399c8f683d to your computer and use it in GitHub Desktop.
Polymorphic JSON parsing with Kotlinx Serialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| val response: MyFoodWrapper = client.get { | |
| apiUrl("url_to_polymorphic_json") | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @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? | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| { | |
| "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