forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCustomConverterTests.Object.cs
756 lines (621 loc) · 26.9 KB
/
CustomConverterTests.Object.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Xunit;
namespace System.Text.Json.Serialization.Tests
{
public static partial class CustomConverterTests
{
/// <summary>
/// A converter that uses Object as it's type.
/// </summary>
private class ObjectToCustomerOrIntConverter : JsonConverter<object>
{
public override bool CanConvert(Type typeToConvert)
{
return (typeToConvert == typeof(Customer) ||
typeToConvert == typeof(int));
}
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (typeToConvert == typeof(Customer))
{
reader.Skip();
Customer c = new Customer();
c.Name = "HelloWorld";
return c;
}
if (typeToConvert == typeof(int))
{
return 42;
}
throw new NotSupportedException();
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
// Write the name of the type.
writer.WriteStringValue(value.GetType().ToString());
}
}
[Fact]
public static void CustomObjectConverter()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new ObjectToCustomerOrIntConverter());
{
var customer = new Customer();
string json = JsonSerializer.Serialize<object>(customer, options);
Assert.Contains(typeof(Customer).ToString(), json);
json = JsonSerializer.Serialize(customer, options);
Assert.Contains(typeof(Customer).ToString(), json);
}
{
string json = JsonSerializer.Serialize(42, options);
Assert.Contains(typeof(int).ToString(), json);
}
{
object obj = JsonSerializer.Deserialize<Customer>("{}", options);
Assert.IsType<Customer>(obj);
Assert.Equal("HelloWorld", ((Customer)obj).Name);
}
{
// The converter doesn't handle object.
object obj = JsonSerializer.Deserialize<object>("{}", options);
Assert.IsType<JsonElement>(obj);
}
{
int obj = JsonSerializer.Deserialize<int>("0", options);
Assert.Equal(42, obj);
}
}
/// <summary>
/// A converter that converts "true" and "false" tokens to a bool.
/// </summary>
private class ObjectToBoolConverter : JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.True)
{
return true;
}
if (reader.TokenType == JsonTokenType.False)
{
return false;
}
// Use JsonElement as fallback.
var converter = options.GetConverter(typeof(JsonElement)) as JsonConverter<JsonElement>;
if (converter != null)
{
return converter.Read(ref reader, typeToConvert, options);
}
// Shouldn't get here.
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
throw new InvalidOperationException("Directly writing object not supported");
}
}
[Fact]
public static void CustomObjectBoolConverter()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new ObjectToBoolConverter());
{
object obj = JsonSerializer.Deserialize<object>("true", options);
Assert.IsType<bool>(obj);
Assert.True((bool)obj);
}
{
object obj = JsonSerializer.Deserialize<object>("false", options);
Assert.IsType<bool>(obj);
Assert.False((bool)obj);
}
{
object obj = JsonSerializer.Deserialize<object>("{}", options);
Assert.IsType<JsonElement>(obj);
}
}
private class ObjectToCustomerConverter : JsonConverter<Customer>
{
public override bool CanConvert(Type typeToConvert)
{
return (typeToConvert == typeof(Customer) || typeToConvert == typeof(DerivedCustomer));
}
public override Customer Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
Customer customer = null;
if (typeToConvert == typeof(Customer))
{
customer = new Customer();
}
if (typeToConvert == typeof(DerivedCustomer))
{
customer = new DerivedCustomer();
}
if (customer != null)
{
while (reader.Read())
{
if (reader.TokenType == JsonTokenType.EndObject)
{
return customer;
}
if (reader.TokenType == JsonTokenType.PropertyName)
{
string propertyName = reader.GetString();
reader.Read();
switch (propertyName)
{
case "CreditLimit":
decimal creditLimit = reader.GetDecimal();
customer.CreditLimit = creditLimit - 1;
break;
case "Address":
string city = reader.GetString();
customer.Address.City = string.IsNullOrEmpty(city) ? "NA" : city;
break;
case "Name":
string name = reader.GetString().ToUpper();
customer.Name = name;
break;
}
}
}
return customer;
}
throw new NotSupportedException();
}
public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options)
{
writer.WriteStartObject();
writer.WriteString("Name", value.Name);
writer.WriteNumber("CreditLimit", value.CreditLimit);
writer.WriteString("Address", value.Address.City);
writer.WriteEndObject();
}
}
[Fact]
public static void ClassWithFieldHavingCustomConverterTest()
{
TestClassWithFieldsHavingCustomConverter testObject = new TestClassWithFieldsHavingCustomConverter
{
IntValue = 32,
Name = "John Doe",
Customer = new Customer
{
Name = "Customer Doe",
CreditLimit = 1000
},
DerivedCustomer = new DerivedCustomer
{
Name = "Derived Doe",
CreditLimit = 2000,
Address = new Address { City = "UB" }
}
};
var options = new JsonSerializerOptions();
options.Converters.Add(new ObjectToCustomerConverter());
string json = JsonSerializer.Serialize(testObject, options);
Assert.Equal("{\"Name\":\"John Doe\"," +
"\"Customer\":{\"Name\":\"Customer Doe\",\"CreditLimit\":1000,\"Address\":null}," +
"\"DerivedCustomer\":{\"Name\":\"Derived Doe\",\"CreditLimit\":2000,\"Address\":\"UB\"}," +
"\"NullDerivedCustomer\":null," +
"\"IntValue\":32," +
"\"Message\":null}", json);
TestClassWithFieldsHavingCustomConverter testObj = JsonSerializer.Deserialize<TestClassWithFieldsHavingCustomConverter>(json, options);
Assert.Equal(32, testObj.IntValue);
Assert.Equal("John Doe", testObj.Name);
Assert.Equal("CUSTOMER DOE", testObj.Customer.Name);
Assert.Equal("NA", testObj.Customer.Address.City);
Assert.Equal("DERIVED DOE", testObj.DerivedCustomer.Name);
Assert.Equal(1999, testObj.DerivedCustomer.CreditLimit);
Assert.Equal("UB", testObj.DerivedCustomer.Address.City);
Assert.Null(testObj.NullDerivedCustomer);
}
private class TestClassWithFieldsHavingCustomConverter
{
public string Name { get; set; }
public Customer Customer { get; set; }
public DerivedCustomer DerivedCustomer { get; set; }
public DerivedCustomer NullDerivedCustomer { get; set; }
public int IntValue { get; set; }
public string Message { get; set; }
}
/// <summary>
/// A converter that converts System.Object similar to Newtonsoft's JSON.Net.
/// Only primitives are the same; arrays and objects do not result in the same types.
/// </summary>
private class SystemObjectNewtonsoftCompatibleConverter : JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.True)
{
return true;
}
if (reader.TokenType == JsonTokenType.False)
{
return false;
}
if (reader.TokenType == JsonTokenType.Number)
{
if (reader.TryGetInt64(out long l))
{
return l;
}
return reader.GetDouble();
}
if (reader.TokenType == JsonTokenType.String)
{
if (reader.TryGetDateTime(out DateTime datetime))
{
return datetime;
}
return reader.GetString();
}
// Use JsonElement as fallback.
// Newtonsoft uses JArray or JObject.
using (JsonDocument document = JsonDocument.ParseValue(ref reader))
{
return document.RootElement.Clone();
}
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
Assert.IsType<object>(value);
writer.WriteStartObject();
writer.WriteEndObject();
}
}
private class PrimitiveConverter : JsonConverter<object>
{
public int ReadCallCount { get; private set; }
public int WriteCallCount { get; private set; }
public override bool CanConvert(Type typeToConvert)
=> typeToConvert != typeof(ClassWithPrimitives)
&& typeToConvert != typeof(ClassWithNullablePrimitives);
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
ReadCallCount++;
if (reader.TokenType == JsonTokenType.True)
{
return true;
}
if (reader.TokenType == JsonTokenType.False)
{
return false;
}
if (reader.TokenType == JsonTokenType.Number)
{
if (reader.TryGetInt32(out int i))
{
return i;
}
return reader.GetDouble();
}
if (reader.TokenType == JsonTokenType.String)
{
if (reader.TryGetDateTime(out DateTime datetime))
{
return datetime;
}
return reader.GetString();
}
throw new JsonException();
}
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
{
WriteCallCount++;
if (value is int i)
{
writer.WriteNumberValue(i);
}
else if (value is bool b)
{
writer.WriteBooleanValue(b);
}
else if (value is string s)
{
writer.WriteStringValue(s);
}
else
{
throw new NotSupportedException();
}
}
}
private class ClassWithPrimitives
{
public int MyIntProperty { get; set; }
public bool MyBoolProperty { get; set; }
public string MyStringProperty { get; set; }
#pragma warning disable 0649
public int MyIntField;
public bool MyBoolField;
public string MyStringField;
#pragma warning restore
}
[Fact]
public static void ClassWithPrimitivesObjectConverter()
{
string expected = @"{
""MyIntProperty"":123,
""MyBoolProperty"":true,
""MyStringProperty"":""Hello"",
""MyIntField"":321,
""MyBoolField"":true,
""MyStringField"":""World""
}";
string json;
var converter = new PrimitiveConverter();
var options = new JsonSerializerOptions
{
IncludeFields = true
};
options.Converters.Add(converter);
{
var obj = new ClassWithPrimitives
{
MyIntProperty = 123,
MyBoolProperty = true,
MyStringProperty = "Hello",
MyIntField = 321,
MyBoolField = true,
MyStringField = "World",
};
json = JsonSerializer.Serialize(obj, options);
Assert.Equal(6, converter.WriteCallCount);
JsonTestHelper.AssertJsonEqual(expected, json);
}
{
var obj = JsonSerializer.Deserialize<ClassWithPrimitives>(json, options);
Assert.Equal(6, converter.ReadCallCount);
Assert.Equal(123, obj.MyIntProperty);
Assert.True(obj.MyBoolProperty);
Assert.Equal("Hello", obj.MyStringProperty);
Assert.Equal(321, obj.MyIntField);
Assert.True(obj.MyBoolField);
Assert.Equal("World", obj.MyStringField);
}
}
private class ClassWithNullablePrimitives
{
public int? MyIntProperty { get; set; }
public bool? MyBoolProperty { get; set; }
public string MyStringProperty { get; set; }
#pragma warning disable 0649
public int? MyIntField;
public bool? MyBoolField;
public string MyStringField;
#pragma warning restore
}
[Fact]
public static void ClassWithNullablePrimitivesObjectConverter()
{
string expected = @"{
""MyIntProperty"":123,
""MyBoolProperty"":true,
""MyStringProperty"":""Hello"",
""MyIntField"":321,
""MyBoolField"":true,
""MyStringField"":""World""
}";
string json;
var converter = new PrimitiveConverter();
var options = new JsonSerializerOptions
{
IncludeFields = true
};
options.Converters.Add(converter);
{
var obj = new ClassWithNullablePrimitives
{
MyIntProperty = 123,
MyBoolProperty = true,
MyStringProperty = "Hello",
MyIntField = 321,
MyBoolField = true,
MyStringField = "World",
};
json = JsonSerializer.Serialize(obj, options);
Assert.Equal(6, converter.WriteCallCount);
JsonTestHelper.AssertJsonEqual(expected, json);
}
{
var obj = JsonSerializer.Deserialize<ClassWithNullablePrimitives>(json, options);
Assert.Equal(123, obj.MyIntProperty);
Assert.True(obj.MyBoolProperty);
Assert.Equal("Hello", obj.MyStringProperty);
Assert.Equal(321, obj.MyIntField);
Assert.True(obj.MyBoolField);
Assert.Equal("World", obj.MyStringField);
}
}
[Fact]
public static void SystemObjectNewtonsoftCompatibleConverterDeserialize()
{
var options = new JsonSerializerOptions();
options.Converters.Add(new SystemObjectNewtonsoftCompatibleConverter());
{
const string Value = @"null";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.Null(obj);
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.Null(newtonsoftObj);
}
{
const string Value = @"""mystring""";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.IsType<string>(obj);
Assert.Equal("mystring", obj);
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.IsType<string>(newtonsoftObj);
Assert.Equal(newtonsoftObj, obj);
}
{
const string Value = "true";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.IsType<bool>(obj);
Assert.True((bool)obj);
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.IsType<bool>(newtonsoftObj);
Assert.Equal(newtonsoftObj, obj);
}
{
const string Value = "false";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.IsType<bool>(obj);
Assert.False((bool)obj);
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.IsType<bool>(newtonsoftObj);
Assert.Equal(newtonsoftObj, obj);
}
{
const string Value = "123";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.IsType<long>(obj);
Assert.Equal((long)123, obj);
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.IsType<long>(newtonsoftObj);
Assert.Equal(newtonsoftObj, obj);
}
{
const string Value = "123.45";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.IsType<double>(obj);
Assert.Equal(123.45d, obj);
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.IsType<double>(newtonsoftObj);
Assert.Equal(newtonsoftObj, obj);
}
{
const string Value = @"""2019-01-30T12:01:02Z""";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.IsType<DateTime>(obj);
Assert.Equal(new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc), obj);
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.IsType<DateTime>(newtonsoftObj);
Assert.Equal(newtonsoftObj, obj);
}
{
const string Value = @"""2019-01-30T12:01:02+01:00""";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.IsType<DateTime>(obj);
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.IsType<DateTime>(newtonsoftObj);
Assert.Equal(newtonsoftObj, obj);
}
{
const string Value = "{}";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.IsType<JsonElement>(obj);
// Types are different.
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.IsType<Newtonsoft.Json.Linq.JObject>(newtonsoftObj);
}
{
const string Value = "[]";
object obj = JsonSerializer.Deserialize<object>(Value, options);
Assert.IsType<JsonElement>(obj);
// Types are different.
object newtonsoftObj = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(Value);
Assert.IsType<Newtonsoft.Json.Linq.JArray>(newtonsoftObj);
}
}
[Fact]
public static void SystemObjectNewtonsoftCompatibleConverterSerialize()
{
static void Verify(JsonSerializerOptions options)
{
{
string json = JsonSerializer.Serialize<object>(null, options);
Assert.Equal("null", json);
string newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(null);
Assert.Equal(newtonsoftJson, json);
}
{
const string Value = "mystring";
string json = JsonSerializer.Serialize<object>(Value, options);
Assert.Equal(@"""mystring""", json);
string newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(Value);
Assert.Equal(newtonsoftJson, json);
}
{
string json = JsonSerializer.Serialize<object>(true, options);
Assert.Equal("true", json);
string newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(true);
Assert.Equal(newtonsoftJson, json);
}
{
string json = JsonSerializer.Serialize<object>(false, options);
Assert.Equal("false", json);
string newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(false);
Assert.Equal(newtonsoftJson, json);
}
{
const long Value = 123;
object json = JsonSerializer.Serialize<object>(123, options);
Assert.Equal("123", json);
object newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(Value);
Assert.Equal(newtonsoftJson, json);
}
{
const double Value = 123.45;
object json = JsonSerializer.Serialize<object>(Value, options);
Assert.Equal("123.45", json);
object newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(Value);
Assert.Equal(newtonsoftJson, json);
}
{
var value = new DateTime(2019, 1, 30, 12, 1, 2, DateTimeKind.Utc);
string json = JsonSerializer.Serialize<object>(value, options);
Assert.Equal(@"""2019-01-30T12:01:02Z""", json);
string newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(value);
Assert.Equal(newtonsoftJson, json);
}
{
var value = new DateTimeOffset(2019, 1, 30, 12, 1, 2, new TimeSpan(1, 0, 0));
string json = JsonSerializer.Serialize<object>(value, options);
Assert.Equal(@"""2019-01-30T12:01:02+01:00""", json);
string newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(value);
Assert.Equal(newtonsoftJson, json);
}
{
var value = new object();
string json = JsonSerializer.Serialize<object>(new object(), options);
Assert.Equal("{}", json);
string newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(value);
Assert.Equal(newtonsoftJson, json);
}
{
var value = new int[] { };
string json = JsonSerializer.Serialize<object>(value, options);
Assert.Equal("[]", json);
string newtonsoftJson = Newtonsoft.Json.JsonConvert.SerializeObject(value);
Assert.Equal(newtonsoftJson, json);
}
}
// Results should be the same with or without the custom converter since the
// serializer calls value.GetType() for every property value declared as System.Object.
Verify(new JsonSerializerOptions());
var options = new JsonSerializerOptions();
options.Converters.Add(new SystemObjectNewtonsoftCompatibleConverter());
Verify(options);
}
[Fact]
public static void CanCustomizeSystemObjectSerialization()
{
var options = new JsonSerializerOptions { Converters = { new CustomSystemObjectConverter() } };
string expectedJson = "42";
string actualJson = JsonSerializer.Serialize(new object(), options);
Assert.Equal(expectedJson, actualJson);
}
private class CustomSystemObjectConverter : JsonConverter<object>
{
public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException();
public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options)
=> writer.WriteNumberValue(42);
}
}
}