-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathCustomConverterTests.Polymorphic.cs
More file actions
341 lines (281 loc) · 13.5 KB
/
CustomConverterTests.Polymorphic.cs
File metadata and controls
341 lines (281 loc) · 13.5 KB
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class CustomConverterTests
{
// A polymorphic POCO converter using a type discriminator.
private class PersonConverterWithTypeDiscriminator : JsonConverter<Person>
{
enum TypeDiscriminator
{
Customer = 1,
Employee = 2
}
public override bool CanConvert(Type typeToConvert)
{
return typeof(Person).IsAssignableFrom(typeToConvert);
}
public override Person Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException();
}
reader.Read();
if (reader.TokenType != JsonTokenType.PropertyName)
{
throw new JsonException();
}
string propertyName = reader.GetString();
if (propertyName != "TypeDiscriminator")
{
throw new JsonException();
}
reader.Read();
if (reader.TokenType != JsonTokenType.Number)
{
throw new JsonException();
}
Person value;
TypeDiscriminator typeDiscriminator = (TypeDiscriminator)reader.GetInt32();
switch (typeDiscriminator)
{
case TypeDiscriminator.Customer:
value = new Customer();
break;
case TypeDiscriminator.Employee:
value = new Employee();
break;
default:
throw new JsonException();
}
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return value;
}
if (reader.TokenType == JsonTokenType.PropertyName)
{
propertyName = reader.GetString();
reader.Read();
switch (propertyName)
{
case "CreditLimit":
decimal creditLimit = reader.GetDecimal();
((Customer)value).CreditLimit = creditLimit;
break;
case "OfficeNumber":
string officeNumber = reader.GetString();
((Employee)value).OfficeNumber = officeNumber;
break;
case "Name":
string name = reader.GetString();
value.Name = name;
break;
}
}
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, Person value, JsonSerializerOptions options)
{
writer.WriteStartObject();
if (value is Customer)
{
writer.WriteNumber("TypeDiscriminator", (int)TypeDiscriminator.Customer);
writer.WriteNumber("CreditLimit", ((Customer)value).CreditLimit);
}
else if (value is Employee)
{
writer.WriteNumber("TypeDiscriminator", (int)TypeDiscriminator.Employee);
writer.WriteString("OfficeNumber", ((Employee)value).OfficeNumber);
}
writer.WriteString("Name", value.Name);
writer.WriteEndObject();
}
}
[Fact]
public static void PersonConverterPolymorphicTypeDiscriminator()
{
const string customerJson = @"{""TypeDiscriminator"":1,""CreditLimit"":100.00,""Name"":""C""}";
const string employeeJson = @"{""TypeDiscriminator"":2,""OfficeNumber"":""77a"",""Name"":""E""}";
var options = new JsonSerializerOptions();
options.Converters.Add(new PersonConverterWithTypeDiscriminator());
{
Person person = JsonSerializer.Deserialize<Person>(customerJson, options);
Assert.IsType<Customer>(person);
Assert.Equal(100, ((Customer)person).CreditLimit);
Assert.Equal("C", person.Name);
string json = JsonSerializer.Serialize(person, options);
Assert.Equal(customerJson, json);
}
{
Person person = JsonSerializer.Deserialize<Person>(employeeJson, options);
Assert.IsType<Employee>(person);
Assert.Equal("77a", ((Employee)person).OfficeNumber);
Assert.Equal("E", person.Name);
string json = JsonSerializer.Serialize(person, options);
Assert.Equal(employeeJson, json);
}
}
[Fact]
public static void NullPersonConverterPolymorphicTypeDiscriminator()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new PersonConverterWithTypeDiscriminator());
Person person = JsonSerializer.Deserialize<Person>("null");
Assert.Null(person);
}
// A converter that can serialize an abstract Person type.
private class PersonPolymorphicSerializerConverter : JsonConverter<Person>
{
public override Person Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotSupportedException($"Deserializing not supported. Type={typeToConvert}.");
}
public override void Write(Utf8JsonWriter writer, Person value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, value.GetType(), options);
}
}
[Fact]
public static void PersonConverterSerializerPolymorphic()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new PersonPolymorphicSerializerConverter());
Customer customer = new Customer
{
Name = "C",
CreditLimit = 100
};
{
// Verify the polymorphic case.
Person person = customer;
string json = JsonSerializer.Serialize(person, options);
Assert.Contains(@"""CreditLimit"":100", json);
Assert.Contains(@"""Name"":""C""", json);
Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<Person>(json, options));
string arrayJson = JsonSerializer.Serialize(new Person[] { person }, options);
Assert.Contains(@"""CreditLimit"":100", arrayJson);
Assert.Contains(@"""Name"":""C""", arrayJson);
Assert.Throws<NotSupportedException>(() => JsonSerializer.Deserialize<Person[]>(arrayJson, options));
}
{
// Ensure (de)serialization still works when using a Person-derived type. This does not call the custom converter.
string json = JsonSerializer.Serialize(customer, options);
Assert.Contains(@"""CreditLimit"":100", json);
Assert.Contains(@"""Name"":""C""", json);
customer = JsonSerializer.Deserialize<Customer>(json, options);
Assert.Equal(100, customer.CreditLimit);
Assert.Equal("C", customer.Name);
string arrayJson = JsonSerializer.Serialize(new Customer[] { customer }, options);
Assert.Contains(@"""CreditLimit"":100", arrayJson);
Assert.Contains(@"""Name"":""C""", arrayJson);
Customer[] customers = JsonSerializer.Deserialize<Customer[]>(arrayJson, options);
Assert.Equal(100, customers[0].CreditLimit);
Assert.Equal("C", customers[0].Name);
}
}
[Theory]
[MemberData(nameof(PolymorphicConverter_ShouldRoundtripInAllContexts_GetTestData))]
public static void PolymorphicConverter_ShouldRoundtripInAllContexts<T>(T value, string expectedJson)
{
// Regression test for https://github.com/dotnet/runtime/issues/46522
string json = JsonSerializer.Serialize(value);
Assert.Equal(expectedJson, json);
T deserializedValue = JsonSerializer.Deserialize<T>(json);
json = JsonSerializer.Serialize(deserializedValue);
Assert.Equal(expectedJson, json);
}
public static IEnumerable<object[]> PolymorphicConverter_ShouldRoundtripInAllContexts_GetTestData()
{
var value = new SampleRepro { Value = "string" };
string expectedJson = "\"string\"";
yield return WrapArgs(value, expectedJson);
yield return WrapArgs(new { Value = value }, $@"{{""Value"":{expectedJson}}}");
yield return WrapArgs(new[] { value }, $"[{expectedJson}]");
yield return WrapArgs(new Dictionary<string, SampleRepro> { ["key"] = value }, $@"{{""key"":{expectedJson}}}");
static object[] WrapArgs<T>(T value, string expectedJson) => new object[] { value, expectedJson };
}
public interface IRepro<T>
{
T Value { get; }
}
[JsonConverter(typeof(ReproJsonConverter))]
public class SampleRepro : IRepro<object>
{
public object Value { get; set; }
}
public sealed class ReproJsonConverter : JsonConverter<IRepro<object>>
{
public override bool CanConvert(Type typeToConvert)
{
return typeof(IRepro<object>).IsAssignableFrom(typeToConvert);
}
public override IRepro<object> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return new SampleRepro { Value = JsonSerializer.Deserialize<object>(ref reader, options) };
}
public override void Write(Utf8JsonWriter writer, IRepro<object> value, JsonSerializerOptions options)
{
if (value is null)
{
writer.WriteNullValue();
}
else
{
JsonSerializer.Serialize(writer, value.Value, options);
}
}
}
[Fact]
public static void PolymorphicBaseClassConverter_IsPassedCorrectTypeToConvertParameter()
{
// Regression test for https://github.com/dotnet/runtime/issues/77173
var options = new JsonSerializerOptions { Converters = { new PolymorphicBaseClassConverter() } };
// Sanity check -- returns converter for the base class.
JsonConverter converter = options.GetConverter(typeof(DerivedClass));
Assert.IsAssignableFrom<PolymorphicBaseClassConverter>(converter);
// Validate that the correct typeToConvert parameter is passed in all serialization contexts:
// 1. Typed root value.
// 2. Untyped root value (where the reported regression occured).
// 3. Nested values in POCOs, collections & dictionaries.
DerivedClass result = JsonSerializer.Deserialize<DerivedClass>("{}", options);
Assert.IsType<DerivedClass>(result);
object objResult = JsonSerializer.Deserialize("{}", typeof(DerivedClass), options);
Assert.IsType<DerivedClass>(objResult);
PocoWithDerivedClassProperty pocoResult = JsonSerializer.Deserialize<PocoWithDerivedClassProperty>("""{"Value":{}}""", options);
Assert.IsType<DerivedClass>(pocoResult.Value);
DerivedClass[] arrayResult = JsonSerializer.Deserialize<DerivedClass[]>("[{}]", options);
Assert.IsType<DerivedClass>(arrayResult[0]);
Dictionary<string, DerivedClass> dictResult = JsonSerializer.Deserialize<Dictionary<string, DerivedClass>>("""{"Value":{}}""", options);
Assert.IsType<DerivedClass>(dictResult["Value"]);
}
public class BaseClass
{ }
public class DerivedClass : BaseClass
{ }
public class PocoWithDerivedClassProperty
{
public DerivedClass Value { get; set; }
}
public class PolymorphicBaseClassConverter : JsonConverter<BaseClass>
{
public override bool CanConvert(Type typeToConvert) => typeof(BaseClass).IsAssignableFrom(typeToConvert);
public override BaseClass? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Assert.Equal(typeof(DerivedClass), typeToConvert);
reader.Skip();
return (BaseClass)Activator.CreateInstance(typeToConvert);
}
public override void Write(Utf8JsonWriter writer, BaseClass value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
}
}