Just trying the new serialization library but I failed to use it for “dynamic” objects where it is not a priori clear what classes are expected in the serialized object, e.g. when parsing JSON RPC calls. Here is a simple example of the problem:
{ type: "type", data: {...}}
Here the type field specifies what kind of data object is following. Depending on this type I like to choose the correct data class for the de-serialization of the data object.
Is it possible to partial parse the object? For example:
data class RpcCall(val type: String, val data: ParsedTree)
Depending on the value of type the user can then de-serialize the ParsedTree object to the expected class.
I used this approach in Jackson where I used a custom serializer to keep the data object as a string and then reparsed it at a later point when I know which data class is to be expect.
class KeepAsJsonDeserialzier : JsonDeserializer<String>() {
@Throws(IOException::class, JsonProcessingException::class)
override fun deserialize(jsonParser: JsonParser, context: DeserializationContext): String {
val tree = jsonParser.codec.readTree<TreeNode>(jsonParser)
return tree.toString()
}
}
However, this is not optimal since the data object is parsed twice…
Any other ideas how to do it in a nice way?