-
Notifications
You must be signed in to change notification settings - Fork 151
/
Tests.cs
2972 lines (2604 loc) · 88.3 KB
/
Tests.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
using System;
using System.Collections.Generic;
#if !SILVERLIGHT
using NUnit.Framework;
using System.Data;
#endif
using System.Collections;
using System.Threading;
using fastJSON;
using System.Collections.Specialized;
using System.Reflection.Emit;
using System.Linq.Expressions;
using System.Diagnostics;
using System.Linq;
using System.Dynamic;
using System.IO;
using System.Runtime.Serialization;
//namespace UnitTests
//{
#if SILVERLIGHT
public class TestAttribute : Attribute
{
}
public static class Assert
{
public static void IsNull(object o, string msg)
{
System.Diagnostics.Debug.Assert(o == null, msg);
}
public static void IsNotNull(object o)
{
System.Diagnostics.Debug.Assert(o != null);
}
public static void AreEqual(object e, object a)
{
System.Diagnostics.Debug.Assert(e.Equals(a));
}
public static void IsInstanceOf<T>(object o)
{
System.Diagnostics.Debug.Assert(typeof(T) == o.GetType());
}
}
#endif
public class tests
{
#region [ helpers ]
static int thousandtimes = 1000;
static int fivetimes = 5;
#if !SILVERLIGHT
static DataSet ds = new DataSet();
#endif
//static bool exotic = false;
//static bool dsser = false;
public enum Gender
{
Male,
Female
}
public class colclass
{
public colclass()
{
items = new List<baseclass>();
date = DateTime.Now;
multilineString = @"
AJKLjaskljLA
ahjksjkAHJKS سلام فارسی
AJKHSKJhaksjhAHSJKa
AJKSHajkhsjkHKSJKash
ASJKhasjkKASJKahsjk
";
isNew = true;
booleanValue = true;
ordinaryDouble = 0.001;
gender = Gender.Female;
intarray = new int[5] { 1, 2, 3, 4, 5 };
}
public bool booleanValue { get; set; }
public DateTime date { get; set; }
public string multilineString { get; set; }
public List<baseclass> items { get; set; }
public decimal ordinaryDecimal { get; set; }
public double ordinaryDouble { get; set; }
public bool isNew { get; set; }
public string laststring { get; set; }
public Gender gender { get; set; }
#if !SILVERLIGHT
public DataSet dataset { get; set; }
public Hashtable hash { get; set; }
#endif
public Dictionary<string, baseclass> stringDictionary { get; set; }
public Dictionary<baseclass, baseclass> objectDictionary { get; set; }
public Dictionary<int, baseclass> intDictionary { get; set; }
public Guid? nullableGuid { get; set; }
public decimal? nullableDecimal { get; set; }
public double? nullableDouble { get; set; }
public baseclass[] arrayType { get; set; }
public byte[] bytes { get; set; }
public int[] intarray { get; set; }
}
public static colclass CreateObject(bool exotic, bool dataset)
{
var c = new colclass();
c.booleanValue = true;
c.ordinaryDecimal = 3;
if (exotic)
{
c.nullableGuid = Guid.NewGuid();
#if !SILVERLIGHT
c.hash = new Hashtable();
c.hash.Add(new class1("0", "hello", Guid.NewGuid()), new class2("1", "code", "desc"));
c.hash.Add(new class2("0", "hello", "pppp"), new class1("1", "code", Guid.NewGuid()));
if (dataset)
c.dataset = CreateDataset();
#endif
c.bytes = new byte[1024];
c.stringDictionary = new Dictionary<string, baseclass>();
c.objectDictionary = new Dictionary<baseclass, baseclass>();
c.intDictionary = new Dictionary<int, baseclass>();
c.nullableDouble = 100.003;
c.nullableDecimal = 3.14M;
c.stringDictionary.Add("name1", new class2("1", "code", "desc"));
c.stringDictionary.Add("name2", new class1("1", "code", Guid.NewGuid()));
c.intDictionary.Add(1, new class2("1", "code", "desc"));
c.intDictionary.Add(2, new class1("1", "code", Guid.NewGuid()));
c.objectDictionary.Add(new class1("0", "hello", Guid.NewGuid()), new class2("1", "code", "desc"));
c.objectDictionary.Add(new class2("0", "hello", "pppp"), new class1("1", "code", Guid.NewGuid()));
c.arrayType = new baseclass[2];
c.arrayType[0] = new class1();
c.arrayType[1] = new class2();
}
c.items.Add(new class1("1", "1", Guid.NewGuid()));
c.items.Add(new class2("2", "2", "desc1"));
c.items.Add(new class1("3", "3", Guid.NewGuid()));
c.items.Add(new class2("4", "4", "desc2"));
c.laststring = "" + DateTime.Now;
return c;
}
public class baseclass
{
public string Name { get; set; }
public string Code { get; set; }
}
public class class1 : baseclass
{
public class1() { }
public class1(string name, string code, Guid g)
{
Name = name;
Code = code;
guid = g;
}
public Guid guid { get; set; }
}
public class class2 : baseclass
{
public class2() { }
public class2(string name, string code, string desc)
{
Name = name;
Code = code;
description = desc;
}
public string description { get; set; }
}
public class NoExt
{
[System.Xml.Serialization.XmlIgnore()]
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
public baseclass[] objs { get; set; }
public Dictionary<string, class1> dic { get; set; }
public NoExt intern { get; set; }
}
public class Retclass
{
public object ReturnEntity { get; set; }
public string Name { get; set; }
public string Field1;
public int Field2;
public object obj;
public string ppp { get { return "sdfas df "; } }
public DateTime date { get; set; }
#if !SILVERLIGHT
public DataTable ds { get; set; }
#endif
}
public struct Retstruct
{
public object ReturnEntity { get; set; }
public string Name { get; set; }
public string Field1;
public int Field2;
public string ppp { get { return "sdfas df "; } }
public DateTime date { get; set; }
#if !SILVERLIGHT
public DataTable ds { get; set; }
#endif
}
private static long CreateLong(string s)
{
long num = 0;
bool neg = false;
foreach (char cc in s)
{
if (cc == '-')
neg = true;
else if (cc == '+')
neg = false;
else
{
num *= 10;
num += (int)(cc - '0');
}
}
return neg ? -num : num;
}
#if !SILVERLIGHT
private static DataSet CreateDataset()
{
DataSet ds = new DataSet();
for (int j = 1; j < 3; j++)
{
DataTable dt = new DataTable();
dt.TableName = "Table" + j;
dt.Columns.Add("col1", typeof(int));
dt.Columns.Add("col2", typeof(string));
dt.Columns.Add("col3", typeof(Guid));
dt.Columns.Add("col4", typeof(string));
dt.Columns.Add("col5", typeof(bool));
dt.Columns.Add("col6", typeof(string));
dt.Columns.Add("col7", typeof(string));
ds.Tables.Add(dt);
Random rrr = new Random();
for (int i = 0; i < 100; i++)
{
DataRow dr = dt.NewRow();
dr[0] = rrr.Next(int.MaxValue);
dr[1] = "" + rrr.Next(int.MaxValue);
dr[2] = Guid.NewGuid();
dr[3] = "" + rrr.Next(int.MaxValue);
dr[4] = true;
dr[5] = "" + rrr.Next(int.MaxValue);
dr[6] = "" + rrr.Next(int.MaxValue);
dt.Rows.Add(dr);
}
}
return ds;
}
#endif
public class RetNestedclass
{
public Retclass Nested { get; set; }
}
#endregion
[TestFixtureSetUp]
public static void setup()
{
//fastJSON.JSON.Parameters = new JSONParameters();
JSON.Parameters.FixValues();
}
[Test]
public static void objectarray()
{
var o = new object[] { 1, "sdaffs", DateTime.Now };
var s = JSON.ToJSON(o);
var p = JSON.ToObject(s);
}
[Test]
public static void ClassTest()
{
Retclass r = new Retclass();
r.Name = "hello";
r.Field1 = "dsasdF";
r.Field2 = 2312;
r.date = DateTime.Now;
#if !SILVERLIGHT
r.ds = CreateDataset().Tables[0];
#endif
var s = JSON.ToJSON(r);
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject(s);
Assert.AreEqual(2312, (o as Retclass).Field2);
}
[Test]
public static void StructTest()
{
Retstruct r = new Retstruct();
r.Name = "hello";
r.Field1 = "dsasdF";
r.Field2 = 2312;
r.date = DateTime.Now;
#if !SILVERLIGHT
r.ds = CreateDataset().Tables[0];
#endif
var s = JSON.ToJSON(r);
Console.WriteLine(s);
var o = JSON.ToObject(s);
Assert.NotNull(o);
Assert.AreEqual(2312, ((Retstruct)o).Field2);
}
[Test]
public static void ParseTest()
{
Retclass r = new Retclass();
r.Name = "hello";
r.Field1 = "dsasdF";
r.Field2 = 2312;
r.date = DateTime.Now;
#if !SILVERLIGHT
r.ds = CreateDataset().Tables[0];
#endif
var s = JSON.ToJSON(r);
Console.WriteLine(s);
var o = JSON.Parse(s);
Assert.IsNotNull(o);
}
[Test]
public static void StringListTest()
{
List<string> ls = new List<string>();
ls.AddRange(new string[] { "a", "b", "c", "d" });
var s = JSON.ToJSON(ls);
Console.WriteLine(s);
var o = JSON.ToObject(s);
Assert.IsNotNull(o);
}
[Test]
public static void IntListTest()
{
List<int> ls = new List<int>();
ls.AddRange(new int[] { 1, 2, 3, 4, 5, 10 });
var s = JSON.ToJSON(ls);
Console.WriteLine(s);
var p = JSON.Parse(s);
var o = JSON.ToObject(s); // long[] {1,2,3,4,5,10}
Assert.IsNotNull(o);
}
[Test]
public static void List_int()
{
List<int> ls = new List<int>();
ls.AddRange(new int[] { 1, 2, 3, 4, 5, 10 });
var s = JSON.ToJSON(ls);
Console.WriteLine(s);
var p = JSON.Parse(s);
var o = JSON.ToObject<List<int>>(s);
Assert.IsNotNull(o);
}
[Test]
public static void Variables()
{
var s = JSON.ToJSON(42);
var o = JSON.ToObject(s);
Assert.AreEqual(o, 42);
s = JSON.ToJSON("hello");
o = JSON.ToObject(s);
Assert.AreEqual(o, "hello");
s = JSON.ToJSON(42.42M);
o = JSON.ToObject(s);
Assert.AreEqual(42.42M, o);
}
[Test]
public static void Dictionary_String_RetClass()
{
Dictionary<string, Retclass> r = new Dictionary<string, Retclass>();
r.Add("11", new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
r.Add("12", new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
var s = JSON.ToJSON(r);
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<Dictionary<string, Retclass>>(s);
Assert.AreEqual(2, o.Count);
}
[Test]
public static void Dictionary_String_RetClass_noextensions()
{
Dictionary<string, Retclass> r = new Dictionary<string, Retclass>();
r.Add("11", new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
r.Add("12", new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
var s = JSON.ToJSON(r, new fastJSON.JSONParameters { UseExtensions = false });
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<Dictionary<string, Retclass>>(s);
Assert.AreEqual(2, o.Count);
}
[Test]
public static void Dictionary_int_RetClass()
{
Dictionary<int, Retclass> r = new Dictionary<int, Retclass>();
r.Add(11, new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
r.Add(12, new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
var s = JSON.ToJSON(r);
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<Dictionary<int, Retclass>>(s);
Assert.AreEqual(2, o.Count);
}
[Test]
public static void Dictionary_int_RetClass_noextensions()
{
Dictionary<int, Retclass> r = new Dictionary<int, Retclass>();
r.Add(11, new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
r.Add(12, new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
var s = JSON.ToJSON(r, new fastJSON.JSONParameters { UseExtensions = false });
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<Dictionary<int, Retclass>>(s);
Assert.AreEqual(2, o.Count);
}
[Test]
public static void Dictionary_Retstruct_RetClass()
{
Dictionary<Retstruct, Retclass> r = new Dictionary<Retstruct, Retclass>();
r.Add(new Retstruct { Field1 = "111", Field2 = 1, date = DateTime.Now }, new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
r.Add(new Retstruct { Field1 = "222", Field2 = 2, date = DateTime.Now }, new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
var s = JSON.ToJSON(r);
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<Dictionary<Retstruct, Retclass>>(s);
Assert.AreEqual(2, o.Count);
}
[Test]
public static void Dictionary_Retstruct_RetClass_noextentions()
{
Dictionary<Retstruct, Retclass> r = new Dictionary<Retstruct, Retclass>();
r.Add(new Retstruct { Field1 = "111", Field2 = 1, date = DateTime.Now }, new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
r.Add(new Retstruct { Field1 = "222", Field2 = 2, date = DateTime.Now }, new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
var s = JSON.ToJSON(r, new fastJSON.JSONParameters { UseExtensions = false });
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<Dictionary<Retstruct, Retclass>>(s);
Assert.AreEqual(2, o.Count);
}
[Test]
public static void List_RetClass()
{
List<Retclass> r = new List<Retclass>();
r.Add(new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
r.Add(new Retclass { Field1 = "222", Field2 = 3, date = DateTime.Now });
var s = JSON.ToJSON(r);
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<List<Retclass>>(s);
Assert.AreEqual(2, o.Count);
}
[Test]
public static void List_RetClass_noextensions()
{
List<Retclass> r = new List<Retclass>();
r.Add(new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now });
r.Add(new Retclass { Field1 = "222", Field2 = 3, date = DateTime.Now });
var s = JSON.ToJSON(r, new fastJSON.JSONParameters { UseExtensions = false });
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<List<Retclass>>(s);
Assert.AreEqual(2, o.Count);
}
[Test]
public static void Perftest()
{
string s = "123456";
DateTime dt = DateTime.Now;
int c = 1000000;
for (int i = 0; i < c; i++)
{
var o = CreateLong(s);
}
Console.WriteLine("convertlong (ms): " + DateTime.Now.Subtract(dt).TotalMilliseconds);
dt = DateTime.Now;
for (int i = 0; i < c; i++)
{
var o = long.Parse(s);
}
Console.WriteLine("long.parse (ms): " + DateTime.Now.Subtract(dt).TotalMilliseconds);
dt = DateTime.Now;
for (int i = 0; i < c; i++)
{
var o = Convert.ToInt64(s);
}
Console.WriteLine("convert.toint64 (ms): " + DateTime.Now.Subtract(dt).TotalMilliseconds);
}
[Test]
public static void FillObject()
{
NoExt ne = new NoExt();
ne.Name = "hello";
ne.Address = "here";
ne.Age = 10;
ne.dic = new Dictionary<string, class1>();
ne.dic.Add("hello", new class1("asda", "asdas", Guid.NewGuid()));
ne.objs = new baseclass[] { new class1("a", "1", Guid.NewGuid()), new class2("b", "2", "desc") };
string str = JSON.ToJSON(ne, new fastJSON.JSONParameters { UseExtensions = false, UsingGlobalTypes = false });
string strr = JSON.Beautify(str);
Console.WriteLine(strr);
object dic = JSON.Parse(str);
object oo = JSON.ToObject<NoExt>(str);
NoExt nee = new NoExt();
nee.intern = new NoExt { Name = "aaa" };
JSON.FillObject(nee, strr);
}
[Test]
public static void AnonymousTypes()
{
var q = new { Name = "asassa", Address = "asadasd", Age = 12 };
string sq = JSON.ToJSON(q, new JSONParameters { EnableAnonymousTypes = true });
Console.WriteLine(sq);
Assert.AreEqual("{\"Name\":\"asassa\",\"Address\":\"asadasd\",\"Age\":12}", sq);
}
[Test]
public static void Speed_Test_Deserialize()
{
Console.Write("fastjson deserialize");
JSON.Parameters = new JSONParameters();
colclass c = CreateObject(false, false);
double t = 0;
var stopwatch = new Stopwatch();
for (int pp = 0; pp < fivetimes; pp++)
{
stopwatch.Restart();
colclass deserializedStore;
string jsonText = JSON.ToJSON(c);
//Console.WriteLine(" size = " + jsonText.Length);
for (int i = 0; i < thousandtimes; i++)
{
deserializedStore = (colclass)JSON.ToObject(jsonText);
}
stopwatch.Stop();
t += stopwatch.ElapsedMilliseconds;
Console.Write("\t" + stopwatch.ElapsedMilliseconds);
}
Console.WriteLine("\tAVG = " + t / fivetimes);
}
[Test]
public static void Speed_Test_Serialize()
{
Console.Write("fastjson serialize");
JSON.Parameters = new JSONParameters();
//fastJSON.JSON.Parameters.UsingGlobalTypes = false;
colclass c = CreateObject(false, false);
double t = 0;
var stopwatch = new Stopwatch();
for (int pp = 0; pp < fivetimes; pp++)
{
stopwatch.Restart();
string jsonText = null;
for (int i = 0; i < thousandtimes; i++)
{
jsonText = JSON.ToJSON(c);
}
stopwatch.Stop();
t += stopwatch.ElapsedMilliseconds;
Console.Write("\t" + stopwatch.ElapsedMilliseconds);
}
Console.WriteLine("\tAVG = " + t / fivetimes);
}
[Test]
public static void List_NestedRetClass()
{
List<RetNestedclass> r = new List<RetNestedclass>();
r.Add(new RetNestedclass { Nested = new Retclass { Field1 = "111", Field2 = 2, date = DateTime.Now } });
r.Add(new RetNestedclass { Nested = new Retclass { Field1 = "222", Field2 = 3, date = DateTime.Now } });
var s = JSON.ToJSON(r);
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<List<RetNestedclass>>(s);
Assert.AreEqual(2, o.Count);
}
[Test]
public static void NullTest()
{
var s = JSON.ToJSON(null);
Assert.AreEqual("null", s);
var o = JSON.ToObject(s);
Assert.AreEqual(null, o);
o = JSON.ToObject<class1>(s);
Assert.AreEqual(null, o);
}
[Test]
public static void DisableExtensions()
{
var p = new fastJSON.JSONParameters { UseExtensions = false, SerializeNullValues = false };
var s = JSON.ToJSON(new Retclass { date = DateTime.Now, Name = "aaaaaaa" }, p);
Console.WriteLine(JSON.Beautify(s));
var o = JSON.ToObject<Retclass>(s);
Assert.AreEqual("aaaaaaa", o.Name);
}
[Test]
public static void ZeroArray()
{
var s = JSON.ToJSON(new object[] { });
var o = JSON.ToObject(s);
var a = o as object[];
Assert.AreEqual(0, a.Length);
}
[Test]
public static void BigNumber()
{
double d = 4.16366160299608e18;
var s = JSON.ToJSON(d);
var o = JSON.ToObject<double>(s);
Assert.AreEqual(d, o);
}
[Test]
public static void GermanNumbers()
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("de");
decimal d = 3.141592654M;
var s = JSON.ToJSON(d);
var o = JSON.ToObject<decimal>(s);
Assert.AreEqual(d, o);
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en");
}
private static void GenerateJsonForAandB(out string jsonA, out string jsonB)
{
Console.WriteLine("Begin constructing the original objects. Please ignore trace information until I'm done.");
// set all parameters to false to produce pure JSON
JSON.Parameters = new JSONParameters { EnableAnonymousTypes = false, SerializeNullValues = false, UseExtensions = false, UseFastGuid = false, UseOptimizedDatasetSchema = false, UseUTCDateTime = false, UsingGlobalTypes = false };
var a = new ConcurrentClassA { PayloadA = new PayloadA() };
var b = new ConcurrentClassB { PayloadB = new PayloadB() };
// A is serialized with extensions and global types
jsonA = JSON.ToJSON(a, new JSONParameters { EnableAnonymousTypes = false, SerializeNullValues = false, UseExtensions = true, UseFastGuid = false, UseOptimizedDatasetSchema = false, UseUTCDateTime = false, UsingGlobalTypes = true });
// B is serialized using the above defaults
jsonB = JSON.ToJSON(b);
Console.WriteLine("Ok, I'm done constructing the objects. Below is the generated json. Trace messages that follow below are the result of deserialization and critical for understanding the timing.");
Console.WriteLine(jsonA);
Console.WriteLine(jsonB);
}
[Test]
public void UsingGlobalsBug_singlethread()
{
var p = JSON.Parameters;
string jsonA;
string jsonB;
GenerateJsonForAandB(out jsonA, out jsonB);
var ax = JSON.ToObject(jsonA); // A has type information in JSON-extended
var bx = JSON.ToObject<ConcurrentClassB>(jsonB); // B needs external type info
Assert.IsNotNull(ax);
Assert.IsInstanceOf<ConcurrentClassA>(ax);
Assert.IsNotNull(bx);
Assert.IsInstanceOf<ConcurrentClassB>(bx);
JSON.Parameters = p;
}
[Test]
public static void NullOutput()
{
var c = new ConcurrentClassA();
var s = JSON.ToJSON(c, new JSONParameters { UseExtensions = false, SerializeNullValues = false });
Console.WriteLine(JSON.Beautify(s));
Assert.AreEqual(false, s.Contains(",")); // should not have a comma
}
[Test]
public void UsingGlobalsBug_multithread()
{
var p = JSON.Parameters;
string jsonA;
string jsonB;
GenerateJsonForAandB(out jsonA, out jsonB);
object ax = null;
object bx = null;
/*
* Intended timing to force CannotGetType bug in 2.0.5:
* the outer class ConcurrentClassA is deserialized first from json with extensions+global types. It reads the global types and sets _usingglobals to true.
* The constructor contains a sleep to force parallel deserialization of ConcurrentClassB while in A's constructor.
* The deserialization of B sets _usingglobals back to false.
* After B is done, A continues to deserialize its PayloadA. It finds type "2" but since _usingglobals is false now, it fails with "Cannot get type".
*/
Exception exception = null;
var thread = new Thread(() =>
{
try
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " A begins deserialization");
ax = JSON.ToObject(jsonA); // A has type information in JSON-extended
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " A is done");
}
catch (Exception ex)
{
exception = ex;
}
});
thread.Start();
Thread.Sleep(500); // wait to allow A to begin deserialization first
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " B begins deserialization");
bx = JSON.ToObject<ConcurrentClassB>(jsonB); // B needs external type info
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " B is done");
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " waiting for A to continue");
thread.Join(); // wait for completion of A due to Sleep in A's constructor
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " threads joined.");
Assert.IsNull(exception, exception == null ? "" : exception.Message + " " + exception.StackTrace);
Assert.IsNotNull(ax);
Assert.IsInstanceOf<ConcurrentClassA>(ax);
Assert.IsNotNull(bx);
Assert.IsInstanceOf<ConcurrentClassB>(bx);
JSON.Parameters = p;
}
public class ConcurrentClassA
{
public ConcurrentClassA()
{
Console.WriteLine("ctor ConcurrentClassA. I will sleep for 2 seconds.");
Thread.Sleep(2000);
Thread.MemoryBarrier(); // just to be sure the caches on multi-core processors do not hide the bug. For me, the bug is present without the memory barrier, too.
Console.WriteLine("ctor ConcurrentClassA. I am done sleeping.");
}
public PayloadA PayloadA { get; set; }
}
public class ConcurrentClassB
{
public ConcurrentClassB()
{
Console.WriteLine("ctor ConcurrentClassB.");
}
public PayloadB PayloadB { get; set; }
}
public class PayloadA
{
public PayloadA()
{
Console.WriteLine("ctor PayLoadA.");
}
}
public class PayloadB
{
public PayloadB()
{
Console.WriteLine("ctor PayLoadB.");
}
}
public class commaclass
{
public string Name = "aaa";
}
public class arrayclass
{
public int[] ints { get; set; }
public string[] strs;
}
[Test]
public static void ArrayTest()
{
arrayclass a = new arrayclass();
a.ints = new int[] { 3, 1, 4 };
a.strs = new string[] { "a", "b", "c" };
var s = JSON.ToJSON(a);
var o = JSON.ToObject(s);
}
#if !SILVERLIGHT
[Test]
public static void SingleCharNumber()
{
sbyte zero = 0;
var s = JSON.ToJSON(zero);
var o = JSON.ToObject(s);
Assert.That(zero, Is.EqualTo(o));
}
[Test]
public static void Datasets()
{
var ds = CreateDataset();
var s = JSON.ToJSON(ds);
var o = JSON.ToObject<DataSet>(s);
var p = JSON.ToObject(s, typeof(DataSet));
Assert.AreEqual(typeof(DataSet), o.GetType());
Assert.IsNotNull(o);
Assert.AreEqual(2, o.Tables.Count);
s = JSON.ToJSON(ds.Tables[0]);
var oo = JSON.ToObject<DataTable>(s);
Assert.IsNotNull(oo);
Assert.AreEqual(typeof(DataTable), oo.GetType());
Assert.AreEqual(100, oo.Rows.Count);
}
[Test]
public static void DynamicTest()
{
string s = "{\"Name\":\"aaaaaa\",\"Age\":10,\"dob\":\"2000-01-01 00:00:00Z\",\"inner\":{\"prop\":30},\"arr\":[1,{\"a\":2},3,4,5,6]}";
dynamic d = JSON.ToDynamic(s);
var ss = d.Name;
var oo = d.Age;
var dob = d.dob;
var inp = d.inner.prop;
var i = d.arr[1].a;
Assert.AreEqual("aaaaaa", ss);
Assert.AreEqual(10, oo);
Assert.AreEqual(30, inp);
Assert.AreEqual("2000-01-01 00:00:00Z", dob);
s = "{\"ints\":[1,2,3,4,5]}";
d = JSON.ToDynamic(s);
var o = d.ints[0];
Assert.AreEqual(1, o);
s = "[1,2,3,4,5,{\"key\":90}]";
d = JSON.ToDynamic(s);
o = d[2];
Assert.AreEqual(3, o);
var p = d[5].key;
Assert.AreEqual(90, p);
}
[Test]
public static void GetDynamicMemberNamesTests()
{
string s = "{\"Name\":\"aaaaaa\",\"Age\":10,\"dob\":\"2000-01-01 00:00:00Z\",\"inner\":{\"prop\":30},\"arr\":[1,{\"a\":2},3,4,5,6]}";
dynamic d = fastJSON.JSON.ToDynamic(s);
Assert.AreEqual(5, d.GetDynamicMemberNames().Count);
Assert.AreEqual(6, d.arr.Count);
Assert.AreEqual("aaaaaa", d["Name"]);
}
#endif
[Test]
public static void CommaTests()
{
var s = JSON.ToJSON(new commaclass(), new JSONParameters());
Console.WriteLine(JSON.Beautify(s));
Assert.AreEqual(true, s.Contains("\"$type\":\"1\","));
var objTest = new
{
A = "foo",
B = (object)null,
C = (object)null,
D = "bar",
E = 12,
F = (object)null
};
var p = new JSONParameters
{
EnableAnonymousTypes = true,
SerializeNullValues = false,
UseExtensions = false,
UseFastGuid = true,
UseOptimizedDatasetSchema = true,
UseUTCDateTime = false,
UsingGlobalTypes = false,
UseEscapedUnicode = false
};
var json = JSON.ToJSON(objTest, p);
Console.WriteLine(JSON.Beautify(json));
Assert.AreEqual("{\"A\":\"foo\",\"D\":\"bar\",\"E\":12}", json);
var o2 = new { A = "foo", B = "bar", C = (object)null };
json = JSON.ToJSON(o2, p);
Console.WriteLine(JSON.Beautify(json));
Assert.AreEqual("{\"A\":\"foo\",\"B\":\"bar\"}", json);
var o3 = new { A = (object)null };
json = JSON.ToJSON(o3, p);
Console.WriteLine(JSON.Beautify(json));
Assert.AreEqual("{}", json);
var o4 = new { A = (object)null, B = "foo" };
json = JSON.ToJSON(o4, p);
Console.WriteLine(JSON.Beautify(json));
Assert.AreEqual("{\"B\":\"foo\"}", json);
}
[Test]
public static void embedded_list()
{
string s = JSON.ToJSON(new { list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, } });//.Where(i => i % 2 == 0) });
}
[Test]
public static void Formatter()
{
string s = "[{\"foo\":\"'[0]\\\"{}\\u1234\\r\\n\",\"bar\":12222,\"coo\":\"some' string\",\"dir\":\"C:\\\\folder\\\\\"}]";
string o = JSON.Beautify(s);
Console.WriteLine(o);