-
Notifications
You must be signed in to change notification settings - Fork 4.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[API Proposal]: attribute for polymorphic json serialisation (not deserialisation) #71605
Comments
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis Issue DetailsBackground and motivationhttps://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-polymorphism "instead of
you should use 'object' as the type of the child:
" The above code doesn't produce an object capable of being deserialised. If we are making people write custom deseralisers for this event, can we at least make the serialisation easy? API Proposala new configuration option for jsonAttribute or jsonserializeroptions to allow for serialisation of objects as the type they actually are, not the type they are referenced as. API Usagepublic class WeatherForecastWithPrevious
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
[JsonAttribute(PolymorphicSerialisation=True)]
public WeatherForecast? PreviousForecast { get; set; }
} Alternative Designsrecommend custom serialisers in this situation, not just custom deserialisers. Risks
|
Closing as duplicate of #63747. Note that the shipped API requires explicitly opting in the supported derived types. |
Background and motivation
https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-polymorphism
says "You can get polymorphic serialization for lower-level objects if you define them as type object."
and provides an example of serializing a derived WeatherForecast via:
"instead of
you should use 'object' as the type of the child:
"
The above code doesn't produce an object capable of being deserialised. If we are making people write custom deseralisers for this event, can we at least make the serialisation easy?
API Proposal
a new configuration option for jsonAttribute or jsonserializeroptions to allow for serialisation of objects as the type they actually are, not the type they are referenced as.
API Usage
Alternative Designs
recommend custom serialisers in this situation, not just custom deserialisers.
Risks
a lack of action here keeps the recommendation to have objects as property types if they might be both inhereted and serialised. This is not inline with good practice.
poor action here will lead people to implement polymorphic serialisation without polymorphic de-serialisation, with silent data loss. (polymorphic deserialisation into object isn't a supported
The text was updated successfully, but these errors were encountered: