I came up with an interesting problem and want to understand how flexible/powerful is Kotlin’s serialization library to help me.
I need to deserialize from
Map<String, Any> - I am getting it from a third-party SDK, which already processes JSON result from network call and creates a
Map for me. This turns out to be a common problem, and the solution suggested from Kotlin team is to convert that map to
JsonObject and then deserialize it.
There is one little problem though - the third party library may put its own SDK objects into that map, once it recognizes them in the JSON result from network (documented here). Those objects are not serializable, I don’t have access to them to modify, and I need them untouched in order to be able to use later with other SDK functionality.
Basically, I can break down the problem to having a serializable class:
@Serializable data class MyClass( val someNumber: Int, val someString: String, val customNonSerializableObject: ThirdPartySDKClass )
and then having a map:
// this object is coming from SDK codes mapOf("someNumber" to 42, "someString" to "hello", "customNonSerializableObject" to ThirdPartySDKClass())
Is there a way I can use kotlin’s serialization to get
MyClass from that map?
The ugly way would be to define
customNonSerializableObject as optional, convert the map to
JsonObject, deserialize it, and then manually assign:
myClassObj.customNonSerializableObject = map["customNonSerializableObject"]
which is basically hardcoding for each endpoint call type.
Maybe somehow define a decoder as shown here, delegate everything to super class, and for the custom objects just copy the reference to the target without any change, is that possible?