-
-
Notifications
You must be signed in to change notification settings - Fork 535
/
JsonInheritanceConverter.liquid
236 lines (197 loc) · 8 KB
/
JsonInheritanceConverter.liquid
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
[System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "{{ ToolchainVersion }}")]
{%- if UseSystemTextJson -%}
internal class JsonInheritanceConverterAttribute : JsonConverterAttribute
{
public string DiscriminatorName { get; }
public JsonInheritanceConverterAttribute(System.Type baseType, string discriminatorName = "discriminator")
: base(typeof(JsonInheritanceConverter<>).MakeGenericType(baseType))
{
DiscriminatorName = discriminatorName;
}
}
internal class JsonInheritanceConverter<TBase> : System.Text.Json.Serialization.JsonConverter<TBase>
{
private readonly string _discriminatorName;
public JsonInheritanceConverter()
{
var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute<JsonInheritanceConverterAttribute>(typeof(TBase));
_discriminatorName = attribute?.DiscriminatorName ?? "discriminator";
}
public JsonInheritanceConverter(string discriminatorName)
{
_discriminatorName = discriminatorName;
}
public virtual string DiscriminatorName => _discriminatorName;
public override TBase Read(ref System.Text.Json.Utf8JsonReader reader, System.Type typeToConvert, System.Text.Json.JsonSerializerOptions options)
{
var document = System.Text.Json.JsonDocument.ParseValue(ref reader);
var hasDiscriminator = document.RootElement.TryGetProperty(_discriminatorName, out var discriminator);
var subtype = GetDiscriminatorType(document.RootElement, typeToConvert, hasDiscriminator ? discriminator.GetString() : null);
var bufferWriter = new System.IO.MemoryStream();
using (var writer = new System.Text.Json.Utf8JsonWriter(bufferWriter))
{
document.RootElement.WriteTo(writer);
}
return (TBase)System.Text.Json.JsonSerializer.Deserialize(bufferWriter.ToArray(), subtype, options);
}
public override void Write(System.Text.Json.Utf8JsonWriter writer, TBase value, System.Text.Json.JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteString(_discriminatorName, GetDiscriminatorValue(value.GetType()));
var bytes = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes((object)value, options);
var document = System.Text.Json.JsonDocument.Parse(bytes);
foreach (var property in document.RootElement.EnumerateObject())
{
property.WriteTo(writer);
}
writer.WriteEndObject();
}
public virtual string GetDiscriminatorValue(System.Type type)
{
var jsonInheritanceAttributeDiscriminator = GetSubtypeDiscriminator(type);
if (jsonInheritanceAttributeDiscriminator != null)
{
return jsonInheritanceAttributeDiscriminator;
}
return type.Name;
}
protected virtual System.Type GetDiscriminatorType(System.Text.Json.JsonElement jObject, System.Type objectType, string discriminatorValue)
{
var jsonInheritanceAttributeSubtype = GetObjectSubtype(objectType, discriminatorValue);
if (jsonInheritanceAttributeSubtype != null)
{
return jsonInheritanceAttributeSubtype;
}
if (objectType.Name == discriminatorValue)
{
return objectType;
}
var typeName = objectType.Namespace + "." + discriminatorValue;
var subtype = System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType).Assembly.GetType(typeName);
if (subtype != null)
{
return subtype;
}
throw new System.InvalidOperationException("Could not find subtype of '" + objectType.Name + "' with discriminator '" + discriminatorValue + "'.");
}
private System.Type GetObjectSubtype(System.Type objectType, string discriminator)
{
foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes<JsonInheritanceAttribute>(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true))
{
if (attribute.Key == discriminator)
return attribute.Type;
}
return objectType;
}
private string GetSubtypeDiscriminator(System.Type objectType)
{
foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes<JsonInheritanceAttribute>(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true))
{
if (attribute.Type == objectType)
return attribute.Key;
}
return objectType.Name;
}
}
{%- else -%}
internal class JsonInheritanceConverter : Newtonsoft.Json.JsonConverter
{
internal static readonly string DefaultDiscriminatorName = "discriminator";
private readonly string _discriminator;
[System.ThreadStatic]
private static bool _isReading;
[System.ThreadStatic]
private static bool _isWriting;
public JsonInheritanceConverter()
{
_discriminator = DefaultDiscriminatorName;
}
public JsonInheritanceConverter(string discriminator)
{
_discriminator = discriminator;
}
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer)
{
try
{
_isWriting = true;
var jObject = Newtonsoft.Json.Linq.JObject.FromObject(value, serializer);
jObject.AddFirst(new Newtonsoft.Json.Linq.JProperty(_discriminator, GetSubtypeDiscriminator(value.GetType())));
writer.WriteToken(jObject.CreateReader());
}
finally
{
_isWriting = false;
}
}
public override bool CanWrite
{
get
{
if (_isWriting)
{
_isWriting = false;
return false;
}
return true;
}
}
public override bool CanRead
{
get
{
if (_isReading)
{
_isReading = false;
return false;
}
return true;
}
}
public override bool CanConvert(System.Type objectType)
{
return true;
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer)
{
var jObject = serializer.Deserialize<Newtonsoft.Json.Linq.JObject>(reader);
if (jObject == null)
return null;
var discriminatorValue = jObject.GetValue(_discriminator);
var discriminator = discriminatorValue != null ? Newtonsoft.Json.Linq.Extensions.Value<string>(discriminatorValue) : null;
var subtype = GetObjectSubtype(objectType, discriminator);
var objectContract = serializer.ContractResolver.ResolveContract(subtype) as Newtonsoft.Json.Serialization.JsonObjectContract;
if (objectContract == null || System.Linq.Enumerable.All(objectContract.Properties, p => p.PropertyName != _discriminator))
{
jObject.Remove(_discriminator);
}
try
{
_isReading = true;
return serializer.Deserialize(jObject.CreateReader(), subtype);
}
finally
{
_isReading = false;
}
}
private System.Type GetObjectSubtype(System.Type objectType, string discriminator)
{
foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes<JsonInheritanceAttribute>(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true))
{
if (attribute.Key == discriminator)
return attribute.Type;
}
return objectType;
}
private string GetSubtypeDiscriminator(System.Type objectType)
{
foreach (var attribute in System.Reflection.CustomAttributeExtensions.GetCustomAttributes<JsonInheritanceAttribute>(System.Reflection.IntrospectionExtensions.GetTypeInfo(objectType), true))
{
if (attribute.Type == objectType)
return attribute.Key;
}
return objectType.Name;
}
}
{%- endif -%}