The newer JSON serializer System.Text.Json introduced in .NET Core 3.0 has offered adaptability of the serialization via so-called Type Info Resolvers since version 7.0. This allows you to customize serialization and deserialization without having to change the .NET class in question. This is useful if the .NET class to be (de-)serialized does not exist in the source code.
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.
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 4.6.2 or later.
The program code in the listing ensures that
With serialization and deserialization of the Point class, the property Memo is ignored and the coordinates X and Y (both declared as numbers of type “int”) can also be deserialized from character strings such as “123” and “456”.
The TypeInfoResolver property in the JsonSerializerOptions is of type IJsonTypeInfoResolver.
///
public class Point
{
public int X { get; set; }
public int Y { get; set; }
public string Memo { get; set; } = “?”;
}
public class FCL_JSON
{
///
public static void JSON_TypeInfoResolver() { CUI.H2(nameof(JSON_TypeInfoResolver)); JsonSerializerOptions options = new() { TypeInfoResolver = new DefaultJsonTypeInfoResolver() { Modifiers = { (JsonTypeInfo jsonTypeInfo) => { // Ignore all properties starting with “Memo” var memoProp = jsonTypeInfo.Properties.FirstOrDefault(p=>p. Name.StartsWith(“Memo”)); if (memoProp != null) { jsonTypeInfo.Properties.Remove(memoProp); } // Allow deserializing numbers from strings if (jsonTypeInfo.Type == typeof(int)) { jsonTypeInfo.NumberHandling = JsonNumberHandling.AllowReadingFromString; } } } } }; // serialization var p1 = new Point() { X = 1, Y = 2, memo = “test point” }; var json1 = JsonSerializer.Serialize(p1, options); Console.WriteLine(json1); // output: {“X”:1,”Y”:2} // deserialization string json2 = “”” { “X”:”123″,”Y”:”456″,”Memo”:”Test position” } “””; Console.WriteLine(“Custom deserialization ofn” + json2); point? p2 = JsonSerializer.Deserialize
if (p2 is not null) Console.WriteLine($”({p2.X},{p2.Y},{p2.Memo})”);
// Ausgabe: (123,456,?)
}
A blog post covers other ways of using the Type Info Resolver.
Advertisement
(rme)
To home page