/
JsonContractCustomizationSample.cs
56 lines (49 loc) · 1.93 KB
/
JsonContractCustomizationSample.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace LibraryApis.DotNet7;
public record Customer
{
public string Name { get; init; } = string.Empty;
public decimal Discount { get; init; }
public string Secret { get; init; } = string.Empty;
}
public static class JsonContractCustomizationSample
{
private static readonly JsonSerializerOptions Options = new()
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers =
{
(JsonTypeInfo jsonTypeInfo) =>
{
// Modify reading and writing decimals
if (jsonTypeInfo.Type == typeof(decimal))
{
jsonTypeInfo.NumberHandling =
JsonNumberHandling.WriteAsString | JsonNumberHandling.AllowReadingFromString;
}
// Ignore some properties by name
if (jsonTypeInfo.Type == typeof(Customer))
{
var allowedProperties =
jsonTypeInfo.Properties.Where(pi => pi.Name != "Secret").ToArray();
jsonTypeInfo.Properties.Clear();
foreach (var property in allowedProperties)
jsonTypeInfo.Properties.Add(property);
}
}
}
}
};
public static void Run()
{
var customer = new Customer { Name = "Test customer", Discount = 15.45m, Secret = "Hidden" };
var json = JsonSerializer.Serialize(customer, Options);
Console.WriteLine($" Customer: {customer}");
Console.WriteLine($" Serialized customer: {json}");
var deserialized = JsonSerializer.Deserialize<Customer>(json, Options);
Console.WriteLine($" Deserialized customer: {deserialized}");
}
}