Goal: Deserialize a nested JSON structure, where the objects instantiated are not instances of the given abstract base type but rather are of the appropriate derived types.
In other words, if the specified destination type is AbstractBaseTpe
, which should be returned is not an instance of that class but rather an instance of ChildTypeA
or ChildTypeB
or GrandchildType1
, etc., as appropriate. This polymorphic deserialization behavior should hold true at the root level (that is, for the type directly returned by JsonSerializer.Deserialize<AbstractBaseType>(…)
), as well as recursively for nested properties (that is, anytime the destination property is of type AbstractBaseType
, the object instantiated for the property should be of the appropriate derived type, like ChildTypeA
, etc.).
Hopefully, one day support for something along these lines will be built into System.Text.Json
. However, for now, when we need it, we have craft our own solution (or borrow one from someone else).
In my case, the other day I needed a simple solution for polymorphic deserialization. Performance wasn’t critical. Just something simple that worked.
Continue reading