-
Notifications
You must be signed in to change notification settings - Fork 38
/
ParserTests.cs
1591 lines (1410 loc) · 70.3 KB
/
ParserTests.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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// On GitHub: https://github.com/ysharplanguage/FastJsonParser
//#define THIS_JSON_PARSER_ONLY // (If *not* defined, the speed tests will require a reference to (at least) Json.NET)
#define RUN_UNIT_TESTS
#define RUN_BASIC_JSONPATH_TESTS
#define RUN_ADVANCED_JSONPATH_TESTS
#define RUN_SERVICESTACK_TESTS // (If defined, the speed tests may require a reference to ServiceStack)
#define RUN_NETJSON_TESTS // (If defined, the speed tests may require a reference to NetJSON)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization; // For Microsoft's JavaScriptSerializer
#if !THIS_JSON_PARSER_ONLY
using Newtonsoft.Json; // Cf. https://www.nuget.org/packages/Newtonsoft.Json
#if RUN_SERVICESTACK_TESTS
using ServiceStack.Text; // Cf. https://www.nuget.org/packages/ServiceStack.Text
#endif
#if RUN_NETJSON_TESTS
using NetJSON; // Cf. https://www.nuget.org/packages/NetJSON
#endif
#endif
using System.Text.Json; // Our stuff; cf. https://www.nuget.org/packages/System.Text.Json
namespace Test
{
#if RUN_UNIT_TESTS && (RUN_BASIC_JSONPATH_TESTS || RUN_ADVANCED_JSONPATH_TESTS)
using System.Text.Json.JsonPath;
using System.Text.Json.JsonPath.LambdaCompilation;
#endif
public class E
{
public object zero { get; set; }
public int one { get; set; }
public int two { get; set; }
public List<int> three { get; set; }
public List<int> four { get; set; }
}
public class F
{
public object g { get; set; }
}
public class E2
{
public F f { get; set; }
}
public class D
{
public E2 e { get; set; }
}
public class C
{
public D d { get; set; }
}
public class B
{
public C c { get; set; }
}
public class A
{
public B b { get; set; }
}
public class H
{
public A a { get; set; }
}
public class HighlyNested
{
public string a { get; set; }
public bool b { get; set; }
public int c { get; set; }
public List<object> d { get; set; }
public E e { get; set; }
public object f { get; set; }
public H h { get; set; }
public List<List<List<List<List<List<List<object>>>>>>> i { get; set; }
}
public class BoonSmall
{
public string debug { get; set; }
public IList<int> nums { get; set; }
}
public enum Status
{
Single,
Married,
Divorced
}
public interface ISomething
{
// Notice how "Name" isn't introduced here yet, but only in the implementation class "Stuff"
int Id { get; set; }
}
public class Stuff : ISomething
{
public int Id { get; set; }
public string Name { get; set; }
public Guid? UniqueId { get; set; } public ulong? LargeUInt { get; set; }
public sbyte SmallInt1 { get; set; } public sbyte SmallInt2 { get; set; }
}
public class StuffHolder
{
public IList<ISomething> Items { get; set; }
}
public class Asset
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public class Owner : Person
{
public IList<Asset> Assets { get; set; }
}
public class Owners
{
public IDictionary<decimal, Owner> OwnerByWealth { get; set; }
public IDictionary<Owner, decimal> WealthByOwner { get; set; }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
// Both string and integral enum value representations can be parsed:
public Status Status { get; set; }
public string Address { get; set; }
// Just to be sure we support that one, too:
public IEnumerable<int> Scores { get; set; }
public object Data { get; set; }
// Generic dictionaries are also supported; e.g.:
// '{
// "Name": "F. Bastiat", ...
// "History": [
// { "key": "1801-06-30", "value": "Birth date" }, ...
// ]
// }'
public IDictionary<DateTime, string> History { get; set; }
// 1-char-long strings in the JSON can be deserialized into System.Char:
public char Abc { get; set; }
}
public enum SomeKey
{
Key0, Key1, Key2, Key3, Key4,
Key5, Key6, Key7, Key8, Key9
}
public class DictionaryData
{
public IList<IDictionary<SomeKey, string>> Dictionaries { get; set; }
}
public class DictionaryDataAdaptJsonNetServiceStack
{
public IList<
IList<KeyValuePair<SomeKey, string>>
> Dictionaries { get; set; }
}
public class FathersData
{
public Father[] fathers { get; set; }
}
public class Someone
{
public string name { get; set; }
}
public class Father : Someone
{
public int id { get; set; }
public bool married { get; set; }
// Lists...
public List<Son> sons { get; set; }
// ... or arrays for collections, that's fine:
public Daughter[] daughters { get; set; }
}
public class Child : Someone
{
public int age { get; set; }
}
public class Son : Child
{
}
public class Daughter : Child
{
public string maidenName { get; set; }
}
public enum VendorID
{
Vendor0,
Vendor1,
Vendor2,
Vendor3,
Vendor4,
Vendor5
}
public class SampleConfigItem
{
public int Id { get; set; }
public string Content { get; set; }
}
public class SampleConfigData<TKey>
{
public Dictionary<TKey, object> ConfigItems { get; set; }
}
#region POCO model for SO question "Json deserializing issue c#" ( http://stackoverflow.com/questions/26426594/json-deserializing-issue-c-sharp )
public class From
{
public string id { get; set; }
public string name { get; set; }
public string category { get; set; }
}
public class Post
{
public string id { get; set; }
public From from { get; set; }
public string message { get; set; }
public string picture { get; set; }
public Dictionary<string, Like[]> likes { get; set; }
}
public class Like
{
public string id { get; set; }
public string name { get; set; }
}
#endregion
#region POCO model for JSONPath Tests (POCO)
public class Data
{
public Store store { get; set; }
}
public class Store
{
public Book[] book { get; set; }
public Bicycle bicycle { get; set; }
}
public class Book
{
public string category { get; set; }
public string author { get; set; }
public string title { get; set; }
public string isbn { get; set; }
public decimal price { get; set; }
}
public class Bicycle
{
public string color { get; set; }
public decimal price { get; set; }
}
#endregion
class ParserTests
{
private static readonly string THE_BURNING_MONK_TEST_FILE_PATH = string.Format(@"..{0}..{0}TestData{0}yan-cui-10k-simple-objects.json.txt", Path.DirectorySeparatorChar);
private static readonly string OJ_TEST_FILE_PATH = string.Format(@"..{0}..{0}TestData{0}_oj-highly-nested.json.txt", Path.DirectorySeparatorChar);
private static readonly string BOON_SMALL_TEST_FILE_PATH = string.Format(@"..{0}..{0}TestData{0}boon-small.json.txt", Path.DirectorySeparatorChar);
private static readonly string TINY_TEST_FILE_PATH = string.Format(@"..{0}..{0}TestData{0}tiny.json.txt", Path.DirectorySeparatorChar);
private static readonly string DICOS_TEST_FILE_PATH = string.Format(@"..{0}..{0}TestData{0}dicos.json.txt", Path.DirectorySeparatorChar);
private static readonly string SMALL_TEST_FILE_PATH = string.Format(@"..{0}..{0}TestData{0}small.json.txt", Path.DirectorySeparatorChar);
private static readonly string TWITTER_TEST_FILE_PATH = string.Format(@"..{0}..{0}TestData{0}twitter.json.txt", Path.DirectorySeparatorChar);
private static readonly string FATHERS_TEST_FILE_PATH = string.Format(@"..{0}..{0}TestData{0}fathers.json.txt", Path.DirectorySeparatorChar);
private static readonly string HUGE_TEST_FILE_PATH = string.Format(@"..{0}..{0}TestData{0}huge.json.txt", Path.DirectorySeparatorChar);
#if RUN_UNIT_TESTS
static object UnitTest<T>(string input, Func<string, T> parse, ref int count, ref int passed) { return UnitTest(input, parse, ref count, ref passed, false); }
static object UnitTest<T>(string input, Func<string, T> parse, ref int count, ref int passed, bool errorCase)
{
object obj;
Console.WriteLine();
Console.WriteLine(errorCase ? "(Error case)" : "(Nominal case)");
Console.WriteLine("\tTry parse: {0} ... as: {1} ...", input, typeof(T).FullName);
try { obj = parse(input); }
catch (Exception ex) { obj = ex; }
Console.WriteLine("\t... result: {0}{1}", (obj != null) ? obj.GetType().FullName : "(null)", (obj is Exception) ? " (" + ((Exception)obj).Message + ")" : String.Empty);
Console.WriteLine();
Console.WriteLine("Press a key...");
Console.WriteLine();
Console.ReadKey();
count++;
if (!errorCase)
{
passed += !(obj is Exception) ? 1 : 0;
}
else
{
passed += (obj is Exception) ? 1 : 0;
}
return obj;
}
static void UnitTests()
{
object obj; int count = 0, passed = 0;
Console.Clear();
Console.WriteLine("Press ESC to skip the unit tests or any other key to start...");
Console.WriteLine();
if (Console.ReadKey().KeyChar == 27)
return;
#if RUN_BASIC_JSONPATH_TESTS || RUN_ADVANCED_JSONPATH_TESTS
#region JSONPath Tests ( http://goessner.net/articles/JsonPath/ )
string input = @"
{ ""store"": {
""book"": [
{ ""category"": ""reference"",
""author"": ""Nigel Rees"",
""title"": ""Sayings of the Century"",
""price"": 8.95
},
{ ""category"": ""fiction"",
""author"": ""Evelyn Waugh"",
""title"": ""Sword of Honour"",
""price"": 12.99
},
{ ""category"": ""fiction"",
""author"": ""Herman Melville"",
""title"": ""Moby Dick"",
""isbn"": ""0-553-21311-3"",
""price"": 8.99,
""status"": ""Married""
},
{ ""category"": ""fiction"",
""author"": ""J. R. R. Tolkien"",
""title"": ""The Lord of the Rings"",
""isbn"": ""0-395-19395-8"",
""price"": 22.99
}
],
""bicycle"": {
""color"": ""red"",
""price"": 19.95
}
}
}
";
JsonPathScriptEvaluator evaluator =
(script, value, context) =>
(value is Type)
? // This holds: (value as Type) == typeof(Func<string, T, IJsonPathContext, object>), with T inferred by JsonPathSelection::SelectNodes(...)
ExpressionParser.Parse((Type)value, script, true, typeof(Data).Namespace).Compile()
:
null;
JsonPathSelection scope;
JsonPathNode[] nodes;
#if RUN_BASIC_JSONPATH_TESTS
var untyped = new JsonParser().Parse(input); // (object untyped = ...)
scope = new JsonPathSelection(untyped); // Cache the JsonPathSelection.
nodes = scope.SelectNodes("$.store.book[3].title"); // Normalized in bracket-notation: $['store']['book'][3]['title']
Assert
(
nodes != null &&
nodes.Length == 1 &&
nodes[0].Value is string &&
nodes[0].As<string>() == "The Lord of the Rings"
);
scope = new JsonPathSelection(untyped, evaluator); // Cache the JsonPathSelection and its lambdas compiled on-demand (at run-time) by the evaluator.
nodes = scope.SelectNodes("$.store.book[?(@.ContainsKey(\"isbn\") && (string)@[\"isbn\"] == \"0-395-19395-8\")].title");
Assert
(
nodes != null &&
nodes.Length == 1 &&
nodes[0].Value is string &&
nodes[0].As<string>() == "The Lord of the Rings"
);
#endif
#if RUN_ADVANCED_JSONPATH_TESTS
var typed = new JsonParser().Parse<Data>(input); // (Data typed = ...)
scope = new JsonPathSelection(typed, evaluator); // Cache the JsonPathSelection and its lambdas compiled on-demand (at run-time) by the evaluator.
nodes = scope.SelectNodes("$.store.book[?(@.title == \"The Lord of the Rings\")].price");
Assert
(
nodes != null &&
nodes.Length == 1 &&
nodes[0].Value is decimal &&
nodes[0].As<decimal>() == 22.99m
);
// Yup. This works too.
nodes = scope.SelectNodes("$.[((@ is Data) ? \"store\" : (string)null)]"); // Dynamic member (property) selection
Assert
(
nodes != null &&
nodes.Length == 1 &&
nodes[0].Value is Store &&
nodes[0].As<Store>() == scope.SelectNodes("$['store']")[0].As<Store>() && // Normalized in bracket-notation
nodes[0].As<Store>() == scope.SelectNodes("$.store")[0].As<Store>() // Common dot-notation
);
// And this, as well. To compare with the above '... nodes = scope.SelectNodes("$.store.book[3].title")'
nodes = scope.
SelectNodes
( // JSONPath expression template...
"$.[{0}].[{1}][{2}].[{3}]",
// ... interpolated with these compile-time lambdas:
(script, value, context) => "store", // Member selector (by name)
(script, value, context) => "book", // Member selector (by name)
(script, value, context) => 1, // Member selector (by index)
(script, value, context) => "title" // Member selector (by name)
);
Assert
(
nodes != null &&
nodes.Length == 1 &&
nodes[0].Value is string &&
nodes[0].As<string>() == "Sword of Honour"
);
// Some JSONPath expressions from Stefan Gössner's JSONPath examples ( http://goessner.net/articles/JsonPath/#e3 )...
// Authors of all books in the store
Assert
(
(nodes = scope.SelectNodes("$.store.book[*].author")).Length == 4
);
// Price of everything in the store
Assert
(
(nodes = scope.SelectNodes("$.store..price")).Length == 5
);
// Third book
Assert
(
(nodes = scope.SelectNodes("$..book[2]"))[0].Value is Book && nodes[0].As<Book>().isbn == "0-553-21311-3"
);
// Last book in order
Assert
(
(nodes = scope.SelectNodes("$..book[(@.Length - 1)]"))[0].Value == scope.SelectNodes("$..book[-1:]")[0].Value
);
// First two books
Assert
(
(nodes = scope.SelectNodes("$..book[0,1]")).Length == scope.SelectNodes("$..book[:2]").Length && nodes.Length == 2
);
// All books with an ISBN
Assert
(
(nodes = scope.SelectNodes("$..book[?(@.isbn)]")).Length == 2
);
// All books cheaper than 10
Assert
(
(nodes = scope.SelectNodes("$..book[?(@.price < 10m)]")).Length == 2
);
// Speaks for itself
var parser = new JsonParser();
var parsed = parser.Parse<FathersData>(System.IO.File.ReadAllText(FATHERS_TEST_FILE_PATH));
var jsonPath = new JsonPathSelection(parsed, evaluator);
var st = Time.Start();
var minorSonCount = jsonPath.SelectNodes("$.fathers[*].sons[?(@.age < 18)]").Length;
var legalSonCount = jsonPath.SelectNodes("$.fathers[*].sons[?(@.age >= 18)]").Length;
var totalSonCount = jsonPath.SelectNodes("$.fathers[*].sons[*]").Length;
var tm = st.ElapsedMilliseconds;
Assert(totalSonCount == minorSonCount + legalSonCount);
Console.WriteLine();
Console.WriteLine("\t\t\t$.fathers[*].sons[?(@.age < 18)]\t:\t{0}", minorSonCount);
Console.WriteLine("\t\t\t$.fathers[*].sons[?(@.age >= 18)]\t:\t{0}", legalSonCount);
Console.WriteLine("\t\t\t$.fathers[*].sons[*]\t\t\t:\t{0}", totalSonCount);
Console.WriteLine();
Console.WriteLine("\t\t\t... in {0} ms.", tm.ToString("0,0"));
Console.WriteLine();
Console.WriteLine("Press a key...");
Console.WriteLine();
Console.ReadKey();
// Anonymous type instance prototype of the target object model,
// used for static type inference by the C# compiler (see below)
var OBJECT_MODEL = new
{
country = new // (Anonymous) country
{
name = default(string),
people = new[] // (Array of...)
{
new // (Anonymous) person
{
initials = default(string),
DOB = default(DateTime),
citizen = default(bool),
status = default(Status) // (Marital "Status" enumeration type)
}
}
}
};
var anonymous = new JsonParser().Parse
(
// Anonymous type instance prototype, passed in
// solely for type inference by the C# compiler
OBJECT_MODEL,
// Input
@"{
""country"": {
""name"": ""USA"",
""people"": [
{
""initials"": ""VV"",
""citizen"": true,
""DOB"": ""1970-03-28"",
""status"": ""Married""
},
{
""DOB"": ""1970-05-10"",
""initials"": ""CJ""
},
{
""initials"": ""RP"",
""DOB"": ""1935-08-20"",
""status"": ""Married"",
""citizen"": true
}
]
}
}"
);
Assert(anonymous.country.people.Length == 3);
foreach (var person in anonymous.country.people)
Assert
(
person.initials.Length == 2 &&
person.DOB > new DateTime(1901, 1, 1)
);
scope = new JsonPathSelection(anonymous, evaluator);
Assert
(
(nodes = scope.SelectNodes(@"$..people[?(!@.citizen)]")).Length == 1 &&
nodes.As(OBJECT_MODEL.country.people[0])[0].initials == "CJ" &&
nodes.As(OBJECT_MODEL.country.people[0])[0].DOB == new DateTime(1970, 5, 10) &&
nodes.As(OBJECT_MODEL.country.people[0])[0].status == Status.Single
);
#endif
#endregion
#endif
// A few nominal cases
obj = UnitTest("null", s => new JsonParser().Parse(s), ref count, ref passed);
Assert(obj == null);
obj = UnitTest("true", s => new JsonParser().Parse(s), ref count, ref passed);
Assert(obj is bool && (bool)obj);
obj = UnitTest(@"""\z""", s => new JsonParser().Parse<char>(s), ref count, ref passed);
Assert(obj is char && (char)obj == 'z');
obj = UnitTest(@"""\t""", s => new JsonParser().Parse<char>(s), ref count, ref passed);
Assert(obj is char && (char)obj == '\t');
obj = UnitTest(@"""\u0021""", s => new JsonParser().Parse<char>(s), ref count, ref passed);
Assert(obj is char && (char)obj == '!');
obj = UnitTest(@"""\u007D""", s => new JsonParser().Parse<char>(s), ref count, ref passed);
Assert(obj is char && (char)obj == '}');
obj = UnitTest(@" ""\u007e"" ", s => new JsonParser().Parse<char>(s), ref count, ref passed);
Assert(obj is char && (char)obj == '~');
obj = UnitTest(@" ""\u202A"" ", s => new JsonParser().Parse<char>(s), ref count, ref passed);
Assert(obj is char && (int)(char)obj == 0x202a);
obj = UnitTest("123", s => new JsonParser().Parse<int>(s), ref count, ref passed);
Assert(obj is int && (int)obj == 123);
obj = UnitTest("\"\"", s => new JsonParser().Parse<string>(s), ref count, ref passed);
Assert(obj is string && (string)obj == String.Empty);
obj = UnitTest("\"Abc\\tdef\"", s => new JsonParser().Parse<string>(s), ref count, ref passed);
Assert(obj is string && (string)obj == "Abc\tdef");
obj = UnitTest("[null]", s => new JsonParser().Parse<object[]>(s), ref count, ref passed);
Assert(obj is object[] && ((object[])obj).Length == 1 && ((object[])obj)[0] == null);
obj = UnitTest("[true]", s => new JsonParser().Parse<IList<bool>>(s), ref count, ref passed);
Assert(obj is IList<bool> && ((IList<bool>)obj).Count == 1 && ((IList<bool>)obj)[0]);
obj = UnitTest("[1,2,3,4,5]", s => new JsonParser().Parse<int[]>(s), ref count, ref passed);
Assert(obj is int[] && ((int[])obj).Length == 5 && ((int[])obj)[4] == 5);
obj = UnitTest("123.456", s => new JsonParser().Parse<decimal>(s), ref count, ref passed);
Assert(obj is decimal && (decimal)obj == 123.456m);
obj = UnitTest("{\"a\":123,\"b\":true}", s => new JsonParser().Parse(s), ref count, ref passed);
Assert(obj is IDictionary<string, object> && (((IDictionary<string, object>)obj)["a"] as string) == "123" && ((obj = ((IDictionary<string, object>)obj)["b"]) is bool) && (bool)obj);
obj = UnitTest("1", s => new JsonParser().Parse<Status>(s), ref count, ref passed);
Assert(obj is Status && (Status)obj == Status.Married);
obj = UnitTest("\"Divorced\"", s => new JsonParser().Parse<Status>(s), ref count, ref passed);
Assert(obj is Status && (Status)obj == Status.Divorced);
obj = UnitTest("{\"Name\":\"Peter\",\"Status\":0}", s => new JsonParser().Parse<Person>(s), ref count, ref passed);
Assert(obj is Person && ((Person)obj).Name == "Peter" && ((Person)obj).Status == Status.Single);
obj = UnitTest("{\"Name\":\"Paul\",\"Status\":\"Married\"}", s => new JsonParser().Parse<Person>(s), ref count, ref passed);
Assert(obj is Person && ((Person)obj).Name == "Paul" && ((Person)obj).Status == Status.Married);
obj = UnitTest("{\"History\":[{\"key\":\"1801-06-30T00:00:00Z\",\"value\":\"Birth date\"}]}", s => new JsonParser().Parse<Person>(s), ref count, ref passed);
Assert(obj is Person && ((Person)obj).History[new DateTime(1801, 6, 30, 0, 0, 0, DateTimeKind.Utc)] == "Birth date");
obj = UnitTest(@"{""Items"":[
{
""__type"": ""Test.Stuff, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"",
""Id"": 123, ""Name"": ""Foo""
},
{
""__type"": ""Test.Stuff, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"",
""Id"": 456, ""Name"": ""Bar"",
""LargeUInt"": 18446744073709551615,
""UniqueId"": ""aad737f7-0caa-4574-9ca5-f39964d50f41"",
""SmallInt1"": 127,
""SmallInt2"": -128
}]}", s => new JsonParser().Parse<StuffHolder>(s), ref count, ref passed);
Assert
(
obj is StuffHolder && ((StuffHolder)obj).Items.Count == 2 &&
((Stuff)((StuffHolder)obj).Items[1]).Name == "Bar" &&
((Stuff)((StuffHolder)obj).Items[1]).UniqueId.HasValue &&
((Stuff)((StuffHolder)obj).Items[1]).UniqueId.Value == new Guid("aad737f7-0caa-4574-9ca5-f39964d50f41") &&
((Stuff)((StuffHolder)obj).Items[1]).LargeUInt.HasValue &&
((Stuff)((StuffHolder)obj).Items[1]).LargeUInt.Value == ulong.MaxValue &&
((Stuff)((StuffHolder)obj).Items[1]).SmallInt1 == sbyte.MaxValue &&
((Stuff)((StuffHolder)obj).Items[1]).SmallInt2 == sbyte.MinValue
);
string configTestInputVendors = @"{
""ConfigItems"": {
""Vendor1"": {
""__type"": ""Test.SampleConfigItem, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"",
""Id"": 100,
""Content"": ""config content for vendor 1""
},
""Vendor3"": {
""__type"": ""Test.SampleConfigItem, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"",
""Id"": 300,
""Content"": ""config content for vendor 3""
}
}
}";
string configTestInputIntegers = @"{
""ConfigItems"": {
""123"": {
""__type"": ""Test.SampleConfigItem, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"",
""Id"": 123000,
""Content"": ""config content for key 123""
},
""456"": {
""__type"": ""Test.SampleConfigItem, Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"",
""Id"": 456000,
""Content"": ""config content for key 456""
}
}
}";
obj = UnitTest(configTestInputVendors, s => new JsonParser().Parse<SampleConfigData<VendorID>>(s), ref count, ref passed);
Assert
(
obj is SampleConfigData<VendorID> &&
((SampleConfigData<VendorID>)obj).ConfigItems.ContainsKey(VendorID.Vendor3) &&
((SampleConfigData<VendorID>)obj).ConfigItems[VendorID.Vendor3] is SampleConfigItem &&
((SampleConfigItem)((SampleConfigData<VendorID>)obj).ConfigItems[VendorID.Vendor3]).Id == 300
);
obj = UnitTest(configTestInputIntegers, s => new JsonParser().Parse<SampleConfigData<int>>(s), ref count, ref passed);
Assert
(
obj is SampleConfigData<int> &&
((SampleConfigData<int>)obj).ConfigItems.ContainsKey(456) &&
((SampleConfigData<int>)obj).ConfigItems[456] is SampleConfigItem &&
((SampleConfigItem)((SampleConfigData<int>)obj).ConfigItems[456]).Id == 456000
);
obj = UnitTest(@"{
""OwnerByWealth"": {
""15999.99"":
{ ""Id"": 1,
""Name"": ""Peter"",
""Assets"": [
{ ""Name"": ""Car"",
""Price"": 15999.99 } ]
},
""250000.05"":
{ ""Id"": 2,
""Name"": ""Paul"",
""Assets"": [
{ ""Name"": ""House"",
""Price"": 250000.05 } ]
}
},
""WealthByOwner"": [
{ ""key"": { ""Id"": 1, ""Name"": ""Peter"" }, ""value"": 15999.99 },
{ ""key"": { ""Id"": 2, ""Name"": ""Paul"" }, ""value"": 250000.05 }
]
}", s => new JsonParser().Parse<Owners>(s), ref count, ref passed);
Owner peter, owner;
Assert
(
(obj is Owners) &&
(peter = ((Owners)obj).WealthByOwner.Keys.
Where(person => person.Name == "Peter").FirstOrDefault()
) != null &&
(owner = ((Owners)obj).OwnerByWealth[15999.99m]) != null &&
(owner.Name == peter.Name) &&
(owner.Assets.Count == 1) &&
(owner.Assets[0].Name == "Car")
);
var nea = (Status?[])UnitTest(@"[1,""Married"",null,2]", s => new JsonParser().Parse<Status?[]>(s), ref count, ref passed);
Assert(nea[0].Value == Status.Married && nea[1].Value == nea[0].Value && !nea[2].HasValue && nea[3].Value == Status.Divorced);
var anon = new { Int1 = default(int?), Stat = default(Status?), Stat2 = default(Status?), Stat3 = default(Status?) };
anon = new JsonParser().Parse(anon, @"{""Int1"":null,""Stat"":1,""Stat3"":null}");
Assert(!anon.Int1.HasValue && anon.Stat == Status.Married && !anon.Stat2.HasValue && !anon.Stat3.HasValue);
var someGuys = @"{
""Jean-Pierre"": ""Single"",
""Jean-Philippe"": 1,
""Jean-Paul"": ""Divorced"",
""Jean-Jacques"": null
}";
var someStatuses =
new JsonParser().Parse<Dictionary<string, Status?>>(someGuys);
var statusCheck =
someStatuses["Jean-Pierre"].Value == Status.Single &&
someStatuses["Jean-Philippe"].Value == Status.Married &&
someStatuses["Jean-Paul"].Value == Status.Divorced &&
!someStatuses["Jean-Jacques"].HasValue; // (we don't know about his...)
Assert(statusCheck);
var someGuys2 = @"{
""Single"": [ ""Jean-Pierre"" ],
""Married"": [ ""Jean-Philippe"" ],
""2"": [ ""Jean-Paul"" ]
}";
var someStatuses2 =
new JsonParser().Parse<Dictionary<Status?, string[]>>(someGuys2);
var statusCheck2 =
someStatuses2[Status.Single][0] == "Jean-Pierre" &&
someStatuses2[Status.Married][0] == "Jean-Philippe" &&
someStatuses2[Status.Divorced][0] == "Jean-Paul";
// (we still don't know about Jean-Jacques' status...)
Assert(statusCheck2);
#if !THIS_JSON_PARSER_ONLY
// Support for Json.NET's "$type" pseudo-key (in addition to ServiceStack's "__type"):
Person jsonNetPerson = new Person { Id = 123, Abc = '#', Name = "Foo", Scores = new[] { 100, 200, 300 } };
// (Expected serialized form shown in next comment)
string jsonNetString = JsonConvert.SerializeObject(jsonNetPerson, new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects });
// => '{"$type":"Test.ParserTests+Person, Test","Id":123,"Name":"Foo","Status":0,"Address":null,"Scores":[100,200,300],"Data":null,"History":null,"Abc":"#"}'
// (Note the Parse<object>(...))
object restoredObject = UnitTest(jsonNetString, s => new JsonParser().Parse<object>(jsonNetString), ref count, ref passed);
Assert
(
restoredObject is Person &&
((Person)restoredObject).Name == "Foo" &&
((Person)restoredObject).Abc == '#' &&
((IList<int>)((Person)restoredObject).Scores).Count == 3 &&
((IList<int>)((Person)restoredObject).Scores)[2] == 300
);
#endif
var SO_26426594_input = @"{ ""data"": [
{
""id"": ""post 1"",
""from"": {
""category"": ""Local business"",
""name"": ""..."",
""id"": ""...""
},
""message"": ""..."",
""picture"": ""..."",
""likes"": {
""data"": [
{
""id"": ""like 1"",
""name"": ""text 1...""
},
{
""id"": ""like 2"",
""name"": ""text 2...""
}
]
}
}
] }";
var posts =
(
UnitTest(
SO_26426594_input,
FacebookPostDeserialization_SO_26426594, ref count, ref passed
) as
Dictionary<string, Post[]>
);
Assert(posts != null && posts["data"][0].id == "post 1");
Assert(posts != null && posts["data"][0].from.category == "Local business");
Assert(posts != null && posts["data"][0].likes["data"][0].id == "like 1");
Assert(posts != null && posts["data"][0].likes["data"][1].id == "like 2");
// A few error cases
obj = UnitTest("\"unfinished", s => new JsonParser().Parse<string>(s), ref count, ref passed, true);
Assert(obj is Exception && ((Exception)obj).Message.StartsWith("Bad string"));
obj = UnitTest("[123]", s => new JsonParser().Parse<string[]>(s), ref count, ref passed, true);
Assert(obj is Exception && ((Exception)obj).Message.StartsWith("Bad string"));
obj = UnitTest("[null]", s => new JsonParser().Parse<short[]>(s), ref count, ref passed, true);
Assert(obj is Exception && ((Exception)obj).Message.StartsWith("Bad number (short)"));
obj = UnitTest("[123.456]", s => new JsonParser().Parse<int[]>(s), ref count, ref passed, true);
Assert(obj is Exception && ((Exception)obj).Message.StartsWith("Unexpected character at 4"));
obj = UnitTest("\"Unknown\"", s => new JsonParser().Parse<Status>(s), ref count, ref passed, true);
Assert(obj is Exception && ((Exception)obj).Message.StartsWith("Bad enum value"));
Console.Clear();
Console.WriteLine("... Unit tests done: {0} passed, out of {1}.", passed, count);
Console.WriteLine();
Console.WriteLine("Press a key to start the speed tests...");
Console.ReadKey();
}
#endif
static void LoopTest<T>(string parserName, Func<string, T> parseFunc, string testFile, int count)
{
Console.Clear();
Console.WriteLine("Parser: {0}", parserName);
Console.WriteLine();
Console.WriteLine("Loop Test File: {0}", testFile);
Console.WriteLine();
Console.WriteLine("Iterations: {0}", count.ToString("0,0"));
Console.WriteLine();
Console.WriteLine("Deserialization: {0}", (typeof(T) != typeof(object)) ? "POCO(s)" : "loosely-typed");
Console.WriteLine();
Console.WriteLine("Press ESC to skip this test or any other key to start...");
Console.WriteLine();
if (Console.ReadKey().KeyChar == 27)
return;
System.Threading.Thread.MemoryBarrier();
var initialMemory = System.GC.GetTotalMemory(true);
var json = System.IO.File.ReadAllText(testFile);
var st = Time.Start();
var l = new List<object>();
for (var i = 0; i < count; i++)
l.Add(parseFunc(json));
var tm = st.ElapsedMilliseconds;
System.Threading.Thread.MemoryBarrier();
var finalMemory = System.GC.GetTotalMemory(true);
var consumption = finalMemory - initialMemory;
Assert(l.Count == count);
Console.WriteLine();
Console.WriteLine("... Done, in {0} ms. Throughput: {1} characters / second.", tm.ToString("0,0"), (1000 * (decimal)(count * json.Length) / (tm > 0 ? tm : 1)).ToString("0,0.00"));
Console.WriteLine();
Console.WriteLine("\tMemory used : {0}", ((decimal)finalMemory).ToString("0,0"));
Console.WriteLine();
GC.Collect();
Console.WriteLine("Press a key...");
Console.WriteLine();
Console.ReadKey();
}
static void Test<T>(string parserName, Func<string, T> parseFunc, string testFile)
{
Test<T>(parserName, parseFunc, testFile, null, null, null);
}
static void Test<T>(string parserName, Func<string, T> parseFunc, string testFile, string jsonPathExpression, Func<object, object> jsonPathSelect, Func<object, bool> jsonPathAssert)
{
var jsonPathTest = !String.IsNullOrWhiteSpace(jsonPathExpression) && (jsonPathSelect != null) && (jsonPathAssert != null);
Console.Clear();
Console.WriteLine("{0}Parser: {1}", (jsonPathTest ? "(With JSONPath selection test) " : String.Empty), parserName);
Console.WriteLine();
Console.WriteLine("Test File: {0}", testFile);
Console.WriteLine();
Console.WriteLine("Deserialization: {0}", (typeof(T) != typeof(object)) ? "POCO(s)" : "loosely-typed");
Console.WriteLine();
if (jsonPathTest)
{
Console.WriteLine("JSONPath expression: {0}", jsonPathExpression);
Console.WriteLine();
}
Console.WriteLine("Press ESC to skip this test or any other key to start...");
Console.WriteLine();
if (Console.ReadKey().KeyChar == 27)
return;
System.Threading.Thread.MemoryBarrier();
var initialMemory = System.GC.GetTotalMemory(true);
var json = System.IO.File.ReadAllText(testFile);
var st = Time.Start();
var o = parseFunc(json);
if (jsonPathTest)
{
var selection = jsonPathSelect(o);
var assertion = jsonPathAssert(selection);
Assert(assertion);
}
var tm = st.ElapsedMilliseconds;
System.Threading.Thread.MemoryBarrier();
var finalMemory = System.GC.GetTotalMemory(true);
var consumption = finalMemory - initialMemory;
Console.WriteLine();
Console.WriteLine("... Done, in {0} ms. Throughput: {1} characters / second.", tm.ToString("0,0"), (1000 * (decimal)json.Length / (tm > 0 ? tm : 1)).ToString("0,0.00"));
Console.WriteLine();
Console.WriteLine("\tMemory used : {0}", ((decimal)finalMemory).ToString("0,0"));
Console.WriteLine();
if (o is FathersData)
{
Console.WriteLine("Fathers : {0}", ((FathersData)(object)o).fathers.Length.ToString("0,0"));
Console.WriteLine();
}
GC.Collect();
Console.WriteLine("Press a key...");
Console.WriteLine();
Console.ReadKey();
}
public sealed class Time
{
private System.Diagnostics.Stopwatch w = System.Diagnostics.Stopwatch.StartNew();
private Time() { }
public static Time Start() { return new Time(); }
public long Reset() { w.Stop(); var t = (long)w.ElapsedMilliseconds; w.Restart(); return t; }
public long ElapsedMilliseconds { get { return Reset(); } }
}
static void SpeedTests()
{
#if !THIS_JSON_PARSER_ONLY
//LoopTest(typeof(JavaScriptSerializer).FullName, new JavaScriptSerializer().Deserialize<TheBurningMonk.RootObject>, THE_BURNING_MONK_TEST_FILE_PATH, 10);
LoopTest(GetVersionString(typeof(JsonConvert).Assembly.GetName()), JsonConvert.DeserializeObject<TheBurningMonk.RootObject>, THE_BURNING_MONK_TEST_FILE_PATH, 10);
#if RUN_SERVICESTACK_TESTS
LoopTest("ServiceStack", new JsonSerializer<TheBurningMonk.RootObject>().DeserializeFromString, THE_BURNING_MONK_TEST_FILE_PATH, 10);