HierarchySerializer
class HierarchySerializer<T : Any>(subTypes: Map<String, Class<out T>>, typeKey: String = TYPE_KEY) : TypeSerializer<T>
A serializer which will delegate (de)serialization to a serializer for a subtype of T based on a string property in a node.
Instances can be constructed either using the default constructor (passing in a map directly) or using a simple DSL model to define subtypes (Model). If unspecified, the default key of the type node is TYPE_KEY.
This serializer must be added through TypeSerializerCollection.Builder.registerExact instead of register
!
Callers must provide a map of strings to subtypes with which nodes will be deserialized:
interface Base
class Foo(val a: Int) : Base
class Bar(val b: String) : Base
HierarchySerializer<Base>( // `<Base>` can be excluded
mapOf(
"foo" to Foo::class.java,
"bar" to Bar::class.java,
),
)
// or
HierarchySerializer<Base> {
// use `_` to omit the `Base` type parameter
subType<_, Foo>("foo")
subType<_, Bar>("bar")
}
Content copied to clipboard
Assuming a structure like:
data class Root(
val items: ArrayList<Base>,
)
Content copied to clipboard
With the typeKey as TYPE_KEY, a possible serialized form would be:
{
"items": [
{
"type": "foo",
"a": 3
},
{
"type": "bar",
"b": "hello"
}
]
}
Content copied to clipboard