-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
CustomConverterTests.List.cs
368 lines (303 loc) · 12.9 KB
/
CustomConverterTests.List.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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class CustomConverterTests
{
// A List{T} converter that used CreateConverter().
private class ListConverter : JsonConverterFactory
{
int _offset;
public ListConverter(int offset)
{
_offset = offset;
}
public override bool CanConvert(Type typeToConvert)
{
if (!typeToConvert.IsGenericType)
return false;
Type generic = typeToConvert.GetGenericTypeDefinition();
if (generic != typeof(List<>))
return false;
Type arg = typeToConvert.GetGenericArguments()[0];
return arg == typeof(int) ||
arg == typeof(long);
}
public override JsonConverter CreateConverter(Type type, JsonSerializerOptions options)
{
Type elementType = type.GetGenericArguments()[0];
JsonConverter converter = (JsonConverter)Activator.CreateInstance(
typeof(ListConverter<>).MakeGenericType(elementType),
BindingFlags.Instance | BindingFlags.Public,
binder: null,
new object[] { _offset },
culture: null);
return converter;
}
}
// Demonstrates List<T>; Adds offset to each integer or long to verify converter ran.
private class ListConverter<T> : JsonConverter<List<T>>
{
private int _offset;
public ListConverter(int offset)
{
_offset = offset;
}
public override List<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartArray)
{
throw new JsonException();
}
var value = new List<T>();
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndArray)
{
return value;
}
if (reader.TokenType != JsonTokenType.Number)
{
throw new JsonException();
}
if (typeof(T) == typeof(int))
{
int element = reader.GetInt32();
IList list = value;
list.Add(element + _offset);
}
else if (typeof(T) == typeof(long))
{
long element = reader.GetInt64();
IList list = value;
list.Add(element + _offset);
}
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, List<T> value, JsonSerializerOptions options)
{
writer.WriteStartArray();
foreach (T item in value)
{
if (item is int)
{
writer.WriteNumberValue((int)(object)item - _offset);
}
else if (item is long)
{
writer.WriteNumberValue((long)(object)item - _offset);
}
else
{
Assert.True(false);
}
}
writer.WriteEndArray();
}
}
[Fact]
public static void ListConverterOpenGeneric()
{
const string json = "[1,2,3]";
var options = new JsonSerializerOptions();
options.Converters.Add(new ListConverter(10));
{
List<int> list = JsonSerializer.Deserialize<List<int>>(json, options);
Assert.Equal(11, list[0]);
Assert.Equal(12, list[1]);
Assert.Equal(13, list[2]);
string jsonSerialized = JsonSerializer.Serialize(list, options);
Assert.Equal(json, jsonSerialized);
}
{
List<long> list = JsonSerializer.Deserialize<List<long>>(json, options);
Assert.Equal(11, list[0]);
Assert.Equal(12, list[1]);
Assert.Equal(13, list[2]);
string jsonSerialized = JsonSerializer.Serialize(list, options);
Assert.Equal(json, jsonSerialized);
}
}
[Fact]
public static void ListConverterClosedGeneric()
{
const string json = "[1,2,3]";
var options = new JsonSerializerOptions();
options.Converters.Add(new ListConverter<int>(10));
List<int> list = JsonSerializer.Deserialize<List<int>>(json, options);
Assert.Equal(11, list[0]);
Assert.Equal(12, list[1]);
Assert.Equal(13, list[2]);
string jsonSerialized = JsonSerializer.Serialize(list, options);
Assert.Equal(json, jsonSerialized);
}
/// <summary>
/// Demonstrates polymorphic IList converter.
/// </summary>
private class IListConverter : JsonConverter<IList>
{
public override bool CanConvert(Type typeToConvert)
{
return typeof(IList).IsAssignableFrom(typeToConvert);
}
public override IList Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartArray)
{
throw new JsonException();
}
var value = new List<int>();
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndArray)
{
return value;
}
int element = reader.GetInt32();
value.Add(element + 10);
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, IList value, JsonSerializerOptions options)
{
writer.WriteStartArray();
foreach (int item in value)
{
writer.WriteNumberValue(item - 10);
}
writer.WriteEndArray();
}
}
[Fact]
public static void ListConverterPolymorphic()
{
const string json = "[1,2,3]";
var options = new JsonSerializerOptions();
options.Converters.Add(new IListConverter());
IList list = JsonSerializer.Deserialize<IList>(json, options);
Assert.Equal(11, list[0]);
Assert.Equal(12, list[1]);
Assert.Equal(13, list[2]);
List<int> contraVariantList = JsonSerializer.Deserialize<List<int>>(json, options);
Assert.Equal(11, contraVariantList[0]);
Assert.Equal(12, contraVariantList[1]);
Assert.Equal(13, contraVariantList[2]);
string jsonSerialized = JsonSerializer.Serialize(list, options);
Assert.Equal(json, jsonSerialized);
jsonSerialized = JsonSerializer.Serialize(contraVariantList, options);
Assert.Equal(json, jsonSerialized);
}
private class MyModelWithConverterAttributes
{
[JsonConverter(typeof(ListToStringElementsConverter))]
public List<string> ItemsList { get; set; }
[JsonConverter(typeof(ListToArrayElementsConverter))]
public string[] ItemsArray { get; set; }
[JsonConverter(typeof(ListToDictionaryElementsConverter))]
public Dictionary<string, string> ItemsDictionary { get; set; }
}
private class MyModelWithNoConverterAttributes
{
public List<string> ItemsList { get; set; }
public string[] ItemsArray { get; set; }
public Dictionary<string, string> ItemsDictionary { get; set; }
}
[Fact]
public static void CustomListWithJsonConverterAttribute()
{
const string Json =
@"{""ItemsList"":[""hello"",1,true]," +
@"""ItemsArray"":[""hello"",1,true]," +
@"""ItemsDictionary"":{""hello"":""hello"",""1"":1,""true"":true}}";
// Baseline failure (no JsonConverterAttributes).
Assert.Throws<JsonException>(() => JsonSerializer.Deserialize<MyModelWithNoConverterAttributes>(Json));
// Success case.
MyModelWithConverterAttributes obj;
void Verify()
{
Assert.Equal("hello", obj.ItemsList[0]);
Assert.Equal("1", obj.ItemsList[1]);
Assert.Equal("True", obj.ItemsList[2]);
Assert.Equal("hello", obj.ItemsArray[0]);
Assert.Equal("1", obj.ItemsArray[1]);
Assert.Equal("True", obj.ItemsArray[2]);
Assert.Equal("hello", obj.ItemsDictionary["hello"]);
Assert.Equal("1", obj.ItemsDictionary["1"]);
Assert.Equal("True", obj.ItemsDictionary["true"]);
}
obj = JsonSerializer.Deserialize<MyModelWithConverterAttributes>(Json);
Verify();
string jsonRoundTripped = JsonSerializer.Serialize<MyModelWithConverterAttributes>(obj);
Assert.Equal(
@"{""ItemsList"":[""hello"",""1"",""True""]," +
@"""ItemsArray"":[""hello"",""1"",""True""]," +
@"""ItemsDictionary"":{""hello"":""hello"",""1"":""1"",""true"":""True""}}",
jsonRoundTripped);
obj = JsonSerializer.Deserialize<MyModelWithConverterAttributes>(jsonRoundTripped);
Verify();
}
/// <summary>
/// This converter coerces JSON array items into <see cref="List{string}"/> when deserializing.
/// </summary>
class ListToStringElementsConverter : JsonConverter<List<string>>
{
public override List<string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using (var doc = JsonDocument.ParseValue(ref reader))
{
return doc.RootElement.EnumerateArray().Select(e => e.ToString()).ToList();
}
}
public override void Write(Utf8JsonWriter writer, List<string> value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, options);
}
}
/// <summary>
/// This converter coerces JSON array items into <see cref="string[]"/> when deserializing.
/// </summary>
class ListToArrayElementsConverter : JsonConverter<string[]>
{
public override string[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using (var doc = JsonDocument.ParseValue(ref reader))
{
return doc.RootElement.EnumerateArray().Select(e => e.ToString()).ToArray();
}
}
public override void Write(Utf8JsonWriter writer, string[] value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, options);
}
}
/// <summary>
/// This converter coerces JSON property values into <see cref="Dictionary{string, string}"> when deserializing.
/// </summary>
class ListToDictionaryElementsConverter : JsonConverter<Dictionary<string, string>>
{
public override Dictionary<string, string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var dictionary = new Dictionary<string, string>();
using (var doc = JsonDocument.ParseValue(ref reader))
{
foreach (JsonProperty property in doc.RootElement.EnumerateObject())
{
dictionary.Add(property.Name, property.Value.ToString());
}
}
return dictionary;
}
public override void Write(Utf8JsonWriter writer, Dictionary<string, string> value, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, value, options);
}
}
}
}