.NET 7 polymorphic serialization support via System.Text.Json #77044
-
Pre .NET 7, System.Text.Json does not support polymorphic serialization, while support was added in .NET 7 (currently RC2), it requires either using attributes on base class or by using custom But I'm a bit confused about the approach taken by .NET 7 to allow opt-in. .NET 7 solution looks like this: [JsonDerivedType(typeof(WeatherForecastWithCity))]
public class WeatherForecastBase
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
}
public class WeatherForecastWithCity : WeatherForecastBase
{
public string? City { get; set; }
}
var data = new WeatherForecastWithCity {...}
var jsonString = JsonSerializer.Serialize<WeatherForecastBase>(data); Which produce this result: {
"City": "Milwaukee",
"Date": "2022-09-26T00:00:00-05:00",
"TemperatureCelsius": 15,
"Summary": "Cool"
} But now we have to declare derived class in // ofc, attribute names are just for explanation
[PolymorphicJsonSerialization]
public class WeatherForecastBase
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string? Summary { get; set; }
}
[PolymorphicJsonSerialization(PolymorphicJsonSerializationMode.Enabled)]
public class WeatherForecastWithCity : WeatherForecastBase
{
public string? City { get; set; }
} This makes sure that derived classes can't just enable this feature by themselves and still keep security concerns in mind. This approach will also allow us to use polymorphics serialization even if both classes are in separate assemblies, while derived class assembly references base class one. So my question is why was current approach selected when it is still so limited. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
How far in the hierarchy would you allow it? Would you allow your class to deserialize into i.e. value in |
Beta Was this translation helpful? Give feedback.
-
See a similar question and the response here. TL;DR there's a few reasons:
For users that do require cross-assembly type hierarchies, it should still be possible to define them using contract customization. |
Beta Was this translation helpful? Give feedback.
See a similar question and the response here. TL;DR there's a few reasons:
For users that do require cross-assembly type hierarchies, it should still be…