Code
·
123 lines
·
2670 bytes
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123# Ignoring JsonSerializer
Emulates jsonIgnore, can be anonymous objects (sort of), aslo filters empty objects! -> object1:{}
## class JsonSerializerIgn
```c#
using System.Collections;
using System.Text.Json.Serialization.Metadata;
namespace System.Text.Json;
public static class JsonSerializerIgn
{
private static string[] Ignoring = [];
private static bool ShouldSerialize(object? value)
{
if (value == null)
return false;
if (value is string s)
return s.Length > 0;
if (value is IList list)
return list.Count > 0;
if (value is bool b)
return b;
if (value is int i)
return i != 0;
if (value is ValueType)
return true;
foreach (var property in value.GetType().GetProperties())
{
if (Array.IndexOf(Ignoring, property.Name) >= 0)
continue;
if (ShouldSerialize(property.GetValue(value)))
return true;
}
return false;
}
public static string Serialize<TValue>(TValue obj,
JsonSerializerOptions? options = null,
string[]? Ignore = null)
{
Ignoring = Ignore ?? ([]);
options ??= new JsonSerializerOptions();
options.TypeInfoResolver = new DefaultJsonTypeInfoResolver()
.WithAddedModifier(typeInfo =>
{
foreach (JsonPropertyInfo propertyInfo in typeInfo.Properties)
propertyInfo.ShouldSerialize = (obj, value) =>
{
if (Array.IndexOf(Ignoring, propertyInfo.Name) >= 0)
return false;
else
return ShouldSerialize(value);
};
});
return JsonSerializer.Serialize(obj, options);
}
}
```
## Test program
```c#
using System.Text.Json;
using VMTux.VMTuxEmulator.DataModel.Form;
namespace ConsoleApp1;
internal class Program
{
async static Task Main(string[] args)
{
var vm = DataEngine.GetVm();
var options = new JsonSerializerOptions() { WriteIndented = true };
var json0 = JsonSerializer.Serialize(vm, options);
var json1 = JsonSerializerIgn.Serialize(vm, options, ["Name1", "Name2", "Name3"]);
await File.WriteAllTextAsync("json0.json", json0);
await File.WriteAllTextAsync("json1.json", json1);
}
}
```
```
## Test program
```c#
using System.Text.Json;
using VMTux.VMTuxEmulator.DataModel.Form;
namespace ConsoleApp1;
internal class Program
{
async static Task Main(string[] args)
{
var vm = DataEngine.GetVm();
var options1 = new JsonSerializerOptions() { WriteIndented = true };
var options2 = new JsonSerializerOptions() { WriteIndented = true };
var json0 = JsonSerializer.Serialize(vm, options1);
var json1 = JsonSerializerIgn.Serialize(vm, options2, ["Name1", "Name2", "Name3"]);
await File.WriteAllTextAsync("json0.json", json0);
await File.WriteAllTextAsync("json1.json", json1);
}
}
```