-
Notifications
You must be signed in to change notification settings - Fork 291
/
Program.cs
48 lines (42 loc) · 1.37 KB
/
Program.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
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
var options = new JsonSerializerOptions
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers =
{
(JsonTypeInfo jsonTypeInfo) =>
{
if (jsonTypeInfo.Type != typeof(Person))
{
return;
}
// Ignore middle name property during serialization
var property = jsonTypeInfo.Properties.First(p => p.Name == nameof(Person.MiddleName));
property.ShouldSerialize = (_, _) => false;
// Allow reading age from string
property = jsonTypeInfo.Properties.First(p => p.Name == nameof(Person.Age));
property.NumberHandling = JsonNumberHandling.AllowReadingFromString;
}
}
}
};
var json = JsonSerializer.Serialize(new Person(), options);
Console.WriteLine(json);
var p = JsonSerializer.Deserialize<Person>("""
{
"FirstName": "John",
"LastName": "Smith",
"Age": "42"
}
""", options)!;
Console.WriteLine(p.Age);
class Person
{
public string FirstName { get; set; } = "Jane";
public string? MiddleName { get; set; } = "Regina";
public string LastName { get; set; } = "Doe";
public int Age { get; set; } = 42;
}