问题
I try to migrate from Newtonsoft.Json to System.Text.Json. I want to deserialize abstract class. Newtonsoft.Json has TypeNameHandling for this. Is there any way to deserialize abstract class via System.Text.Json on .net core 3.0?
回答1:
Please try this library I wrote as an extension to System.Text.Json to offer polymorphism: https://github.com/dahomey-technologies/Dahomey.Json
If the actual type of a reference instance differs from the declared type, the discriminator property will be automatically added to the output json:
public class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureCelsius { get; set; }
public string Summary { get; set; }
}
public class WeatherForecastDerived : WeatherForecast
{
public int WindSpeed { get; set; }
}
Inherited classes must be manually registered to the discriminator convention registry in order to let the framework know about the mapping between a discriminator value and a type:
JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();
DiscriminatorConventionRegistry registry = options.GetDiscriminatorConventionRegistry();
registry.RegisterType<WeatherForecastDerived>();
string json = JsonSerializer.Serialize<WeatherForecast>(weatherForecastDerived, options);
Result:
{
"$type": "Tests.WeatherForecastDerived, Tests",
"Date": "2019-08-01T00:00:00-07:00",
"TemperatureCelsius": 25,
"Summary": "Hot",
"WindSpeed": 35
}
来源:https://stackoverflow.com/questions/58074304/is-polymorphic-deserialization-possible-in-system-text-json