I'm trying to create a web page designer in Blazor. I have a tree data structure. Each tree node corresponds to some Blazor component. All those components have the same base class. I want to serialize this data structure and save it as JSON in database. Then of course I want to read this information back and deserialize it to create exactly the same data structure.
There are a lot of cases where people create some base class and a few derived classes and then they have some data structure (tree, list, dictionary, set, etc.) where they have references to objects of those types. Simple example: Person -> Employee -> Manager. We need a method to correctly (de)serialize these objects.
Thanks for the feedback. We have discussed this previously, and support for polymorphism while serialization will likely be supported (with an opt-in global switch) if the property type is object. I don't believe it will be supported for deserialization though. For an object property, the deserializer will create a JsonElement that encapsulates the JSON payload and set that as the property value.
cc @steveharter, @bartonjs, @rynowak to provide additional context
Yes the plan is to support polymorphic opt-in behavior on serialization only. Likely enabled through an option on JsonSerializerOptions.
The custom converter feature will enable polymorphic deserialization but in a one-off manner.
Moving to future to consider for deserialize. For serialize, this issue now handles.
For Json.NET, there is a third party library which provides subtype discrimination via attributes: https://github.com/manuc66/JsonSubTypes#deserializeobject-with-custom-type-mapping.
Java's Jackson library provides a similar feature called ''Polymorphic Type Handling''', PTH that enables us to select subtype from payload specified by @JsonSubTypes, @JsonTypeInfo attributes.
Would it be too high-level for System.Text.Json to have matching convenience mechanism for polymorphic deserialization out of the box?
This issue mainly discusses polymorphic deserialization - closing as duplicate of https://github.com/dotnet/corefx/issues/39031.
Most helpful comment
For Json.NET, there is a third party library which provides subtype discrimination via attributes: https://github.com/manuc66/JsonSubTypes#deserializeobject-with-custom-type-mapping.
Java's Jackson library provides a similar feature called ''Polymorphic Type Handling''', PTH that enables us to select subtype from payload specified by
@JsonSubTypes,@JsonTypeInfoattributes.Would it be too high-level for System.Text.Json to have matching convenience mechanism for polymorphic deserialization out of the box?