The previous part of this series introduced polymorphism when serializing with System.Text.Json (from version 7.0). The type discriminator also helps with deserialization: Here, too, the JSON deserializer can work polymorphically.
Advertisement
dr Holger Schwichtenberg is Chief Technology Expert at MAXIMAGO, which offers innovation and experience-driven software development, including in highly critical safety-related areas. He is also head of the expert network www.IT-Visions.de, which supports numerous medium-sized and large companies with advice and training in the development and operation of software with 38 renowned experts.
Example
As in the last part, the class Person with its derivation Consultant is used.
[JsonDerivedType(typeof(Person), typeDiscriminator: “P”)]
[JsonDerivedType(typeof(Consultant), typeDiscriminator: “C”)]
public class Person
{
public required int ID { get; set; }
public required string Name { get; set; }
public override string ToString()
{
return $”Person {Name}”;
}
}
public class Consultant : Person
{
public string? Company { get; set; }
public override string ToString()
{
return $”Consultant {Name} arbeitet bei {Company}”;
}
}
A JSON string without the $type suffix
var JSONohneTyp = “””
{“ID”:123,”Company”:”www.IT-Visions.de”,
“Name”:”Holger Schwichtenberg”}
“””;
A consultant object is only created if you explicitly specify the consultant type in Deserialize
Advertisement
A consultant? p1a = JsonSerializer.Deserialize
Console.WriteLine(p1a); // Consultant
Person? p1b =
JsonSerializer.Deserialize
Console.WriteLine(p1b); // Consultant
Person? p1c =
JsonSerializer.Deserialize
Console.WriteLine(p1c); // Person
If there is $type
var JSONmitTyp = “”””
{“$type”:”C”,”ID”:123,
“Company”:”www.IT-Visions.de”,
“Name”:”Holger Schwichtenberg”}
“”””;
you get a consultant object in all three cases, even if you deserialize
Consultant? p2a =
JsonSerializer.Deserialize
Console.WriteLine(p2a); // Consultant
Person? p2b =
JsonSerializer.Deserialize
Console.WriteLine(p2b); // Consultant
Person? p2c =
JsonSerializer.Deserialize
Availability
System.Text.Json was released together with .NET 7.0 as a NuGet package, but also runs under .NET Standard 2.0 and thus also on .NET Core 2.x/3.x and .NET 5.0/.NET 6.0 on the classic .NET Framework from version 4.6.2.
(rme)
To home page