forked from scottcgi/MojoJson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MojoJson.cs
967 lines (763 loc) · 25.5 KB
/
MojoJson.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
/*
* Copyright (c) scott.cgi All Rights Reserved.
*
* This source code belongs to project MojoJson, which is hosted on GitHub, and licensed under the MIT License.
*
* License: https://github.com/scottcgi/MojoJson/blob/master/LICENSE
* GitHub : https://github.com/scottcgi/MojoJson
*
* Since : 2017-9-6
* Update : 2020-2-28
* Author : scott.cgi
* Version: 1.2.2
*/
using System.Collections.Generic;
using System.Text;
using System;
namespace MojoJson
{
public static class Json
{
private const int ObjectInitCapacity = 8;
private const int ArrayInitCapacity = 8;
private static bool isEscapeString;
#region Parse Json API
/// <summary>
/// Parse json string.
/// </summary>
public static JsonValue Parse(string json)
{
var data = new Data(json);
return ParseValue(ref data);
}
/// <summary>
/// Whether the string value need to be escaped ?
/// </summary>
public static void SetEscapeString(bool isEscapeString)
{
Json.isEscapeString = isEscapeString;
}
#endregion
#region Parse Json
/// <summary>
/// Parse the JsonValue.
/// </summary>
private static JsonValue ParseValue(ref Data data)
{
SkipWhiteSpace(ref data);
switch (data.json[data.index])
{
case '{':
return ParseObject(ref data);
case '[':
return ParseArray (ref data);
case '"':
return ParseString(ref data);
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
return ParseNumber(ref data);
case 'f':
if
(
data.json[data.index + 1] == 'a' &&
data.json[data.index + 2] == 'l' &&
data.json[data.index + 3] == 's' &&
data.json[data.index + 4] == 'e'
)
{
data.index += 5;
return new JsonValue(JsonType.Bool, 0.0f);
}
break;
case 't':
if
(
data.json[data.index + 1] == 'r' &&
data.json[data.index + 2] == 'u' &&
data.json[data.index + 3] == 'e'
)
{
data.index += 4;
return new JsonValue(JsonType.Bool, 1.0f);
}
break;
case 'n':
if
(
data.json[data.index + 1] == 'u' &&
data.json[data.index + 2] == 'l' &&
data.json[data.index + 3] == 'l'
)
{
data.index += 4;
return new JsonValue(JsonType.Null, null);
}
break;
}
throw new Exception
(
string.Format
(
"Json ParseValue error on char '{0}' index at '{1}' ",
data.json[data.index],
data.index
)
);
}
/// <summary>
/// Parse JsonObject.
/// </summary>
private static JsonValue ParseObject(ref Data data)
{
var jsonObject = new Dictionary<string, JsonValue>(Json.ObjectInitCapacity);
// skip '{'
++data.index;
do
{
SkipWhiteSpace(ref data);
if (data.json[data.index] == '}')
{
break;
}
DebugTool.Assert
(
data.json[data.index] == '"',
"Json ParseObject error, char '{0}' should be '\"' ",
data.json[data.index]
);
// get object key string
var key = GetString(ref data);
SkipWhiteSpace(ref data);
DebugTool.Assert
(
data.json[data.index] == ':',
"Json ParseObject error, after key = {0}, char '{1}' should be ':' ",
key,
data.json[data.index]
);
// skip ':'
++data.index;
// set JsonObject key and value
jsonObject.Add(key, ParseValue(ref data));
SkipWhiteSpace(ref data);
if (data.json[data.index] == ',')
{
++data.index;
}
else
{
DebugTool.Assert
(
data.json[data.index] == '}',
"Json ParseObject error, after key = {0}, char '{1}' should be '}' ",
key,
data.json[data.index]
);
break;
}
}
while (true);
// skip '}'
++data.index;
return new JsonValue(JsonType.Object, jsonObject);
}
/// <summary>
/// Parse JsonArray.
/// </summary>
private static JsonValue ParseArray(ref Data data)
{
var jsonArray = new List<JsonValue>(Json.ArrayInitCapacity);
// skip '['
++data.index;
do
{
SkipWhiteSpace(ref data);
if (data.json[data.index] == ']')
{
break;
}
// add JsonArray item
jsonArray.Add(ParseValue(ref data));
SkipWhiteSpace(ref data);
if (data.json[data.index] == ',')
{
++data.index;
}
else
{
DebugTool.Assert
(
data.json[data.index] == ']',
"Json ParseArray error, char '{0}' should be ']' ",
data.json[data.index]
);
break;
}
}
while (true);
// skip ']'
++data.index;
return new JsonValue(JsonType.Array, jsonArray);
}
/// <summary>
/// Parses the JsonString.
/// </summary>
private static JsonValue ParseString(ref Data data)
{
string str;
if (Json.isEscapeString == false)
{
str = GetString(ref data);
}
else
{
str = GetEscapedString(ref data);
}
return new JsonValue(JsonType.String, str);
}
/// <summary>
/// Parses the JsonNumber.
/// </summary>
private static JsonValue ParseNumber(ref Data data)
{
var start = data.index;
while (true)
{
switch (data.json[++data.index])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
case '+':
case '.':
case 'e':
case 'E':
continue;
}
break;
}
var strNum = data.json.Substring(start, data.index - start);
if (float.TryParse(strNum, out float num))
{
return new JsonValue(JsonType.Number, num);
}
throw new Exception(string.Format("Json ParseNumber error, cannot parse string [{0}]", strNum));
}
/// <summary>
/// Skip the white space.
/// </summary>
private static void SkipWhiteSpace(ref Data data)
{
while (true)
{
switch (data.json[data.index])
{
case ' ' :
case '\t':
case '\n':
case '\r':
++data.index;
continue;
}
// index point to non-whitespace
break;
}
}
/// <summary>
/// Get the original string value includes escape char.
/// </summary>
private static string GetString(ref Data data)
{
// skip '"'
var start = ++data.index;
while (true)
{
switch (data.json[data.index++])
{
// check end '"'
case '"':
break;
case '\\':
// skip escaped quotes
// the escape char may be '\"',which will break while
++data.index;
continue;
default:
continue;
}
break;
}
// index after the string end '"' so -1
return data.json.Substring(start, data.index - start - 1);
}
/// <summary>
/// Get the escaped string value.
/// </summary>
private static string GetEscapedString(ref Data data)
{
// skip '"'
var start = ++data.index;
string str;
while (true)
{
switch (data.json[data.index++])
{
// check string end '"'
case '"':
if (data.sb.Length == 0)
{
// no escaped char just Substring
str = data.json.Substring(start, data.index - start - 1);
}
else
{
str = data.sb.Append(data.json, start, data.index - start - 1).ToString();
// clear for next string
data.sb.Length = 0;
}
break;
// check escaped char
case '\\':
{
var escapedIndex = data.index;
char c;
switch (data.json[data.index++])
{
case '"':
c = '"';
break;
case '\\':
c = '\\';
break;
case '/':
c = '/';
break;
case '\'':
c = '\'';
break;
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
case 'u':
c = GetUnicodeCodePoint(ref data);
break;
default:
// not support just add in pre string
continue;
}
// add pre string and escaped char
data.sb.Append(data.json, start, escapedIndex - start - 1).Append(c);
// update pre string start index
start = data.index;
continue;
}
default:
continue;
}
// index skipped the string end '"'
break;
}
return str;
}
/// <summary>
/// Get the unicode code point.
/// </summary>
private static char GetUnicodeCodePoint(ref Data data)
{
var index = data.index;
for (var i = 0; i < 4; ++i)
{
char c = data.json[index + i];
switch (c)
{
case '0':
data.unicode[i] = 0;
break;
case '1':
data.unicode[i] = 1;
break;
case '2':
data.unicode[i] = 2;
break;
case '3':
data.unicode[i] = 3;
break;
case '4':
data.unicode[i] = 4;
break;
case '5':
data.unicode[i] = 5;
break;
case '6':
data.unicode[i] = 6;
break;
case '7':
data.unicode[i] = 7;
break;
case '8':
data.unicode[i] = 8;
break;
case '9':
data.unicode[i] = 9;
break;
case 'A':
case 'a':
data.unicode[i] = 10;
break;
case 'B':
case 'b':
data.unicode[i] = 11;
break;
case 'C':
case 'c':
data.unicode[i] = 12;
break;
case 'D':
case 'd':
data.unicode[i] = 13;
break;
case 'E':
case 'e':
data.unicode[i] = 14;
break;
case 'F':
case 'f':
data.unicode[i] = 15;
break;
default:
throw new Exception(string.Format("Json Unicode char '{0}' error", c));
}
}
// skip code point
data.index += 4;
return (char) (
(data.unicode[0] << 12) +
(data.unicode[1] << 8) +
(data.unicode[2] << 4) +
(data.unicode[3] )
);
}
#endregion
private struct Data
{
public readonly string json;
public int index;
public readonly StringBuilder sb;
public readonly int[] unicode;
public Data(string json)
{
this.json = json;
this.index = 0;
this.sb = new StringBuilder();
this.unicode = new int[4];
}
}
}
public enum JsonType
{
Object,
Array,
String,
Number,
Bool,
Null,
}
public class JsonValue
{
public readonly JsonType type;
private readonly object objectValue;
private readonly float numberValue;
public JsonValue(JsonType type, object value)
{
this.type = type;
this.objectValue = value;
}
public JsonValue(JsonType type, float value)
{
this.type = type;
this.numberValue = value;
}
#region JsonObject API
/// <summary>
/// Use JsonValue as JsonObject.
/// </summary>
public Dictionary<string, JsonValue> AsObject()
{
DebugTool.Assert(this.type == JsonType.Object, "JsonValue type is not Object !");
return this.objectValue as Dictionary<string, JsonValue>;
}
/// <summary>
/// Use JsonValue as JsonObject and get JsonValue item by key.
/// return null if not found key.
/// </summary>
public JsonValue AsObjectGet(string key)
{
DebugTool.Assert(this.type == JsonType.Object, "JsonValue type is not Object !");
var dict = this.objectValue as Dictionary<string, JsonValue>;
if (dict.TryGetValue(key, out JsonValue jsonValue))
{
return jsonValue;
}
return null;
}
/// <summary>
/// Use JsonValue as JsonObject and get JsonObject item by key.
/// return null if not found key.
/// </summary>
public Dictionary<string, JsonValue> AsObjectGetObject(string key)
{
var jsonValue = this.AsObjectGet(key);
if (jsonValue != null)
{
return jsonValue.AsObject();
}
return null;
}
/// <summary>
/// Use JsonValue as JsonObject and get JsonArray item by key.
/// return null if not found key.
/// </summary>
public List<JsonValue> AsObjectGetArray(string key)
{
var jsonValue = this.AsObjectGet(key);
if (jsonValue != null)
{
return jsonValue.AsArray();
}
return null;
}
/// <summary>
/// Use JsonValue as JsonObject and get string item by key.
/// return null if not found key.
/// </summary>
public string AsObjectGetString(string key)
{
var jsonValue = this.AsObjectGet(key);
if (jsonValue != null)
{
return jsonValue.AsString();
}
return null;
}
/// <summary>
/// Use JsonValue as JsonObject and get float item by key.
/// return defaultValue if not found key.
/// </summary>
public float AsObjectGetFloat(string key, float defaultValue)
{
var jsonValue = this.AsObjectGet(key);
if (jsonValue != null)
{
return jsonValue.AsFloat();
}
return defaultValue;
}
/// <summary>
/// Use JsonValue as JsonObject and get float item by key.
/// </summary>
public float AsObjectGetFloat(string key)
{
return this.AsObjectGet(key).AsFloat();
}
/// <summary>
/// Use JsonValue as JsonObject and get int item by key.
/// return defaultValue if not found key.
/// </summary>
public int AsObjectGetInt(string key, int defaultValue)
{
var jsonValue = this.AsObjectGet(key);
if (jsonValue != null)
{
return jsonValue.AsInt();
}
return defaultValue;
}
/// <summary>
/// Use JsonValue as JsonObject and get int item by key.
/// </summary>
public int AsObjectGetInt(string key)
{
return this.AsObjectGet(key).AsInt();
}
/// <summary>
/// Use JsonValue as JsonObject and get bool item by key.
/// return defaultValue if not found key.
/// </summary>
public bool AsObjectGetBool(string key, bool defaultValue)
{
var jsonValue = this.AsObjectGet(key);
if (jsonValue != null)
{
return jsonValue.AsBool();
}
return defaultValue;
}
/// <summary>
/// Use JsonValue as JsonObject and get int item by key.
/// </summary>
public bool AsObjectGetBool(string key)
{
return this.AsObjectGet(key).AsBool();
}
/// <summary>
/// Use JsonValue as JsonObject and check null item by key.
/// </summary>
public bool AsObjectGetIsNull(string key)
{
var jsonValue = this.AsObjectGet(key);
if (jsonValue != null)
{
return jsonValue.IsNull();
}
return false;
}
#endregion
#region JsonArray API
/// <summary>
/// Use JsonValue as JsonArray.
/// </summary>
public List<JsonValue> AsArray()
{
DebugTool.Assert(this.type == JsonType.Array, "JsonValue type is not Array !");
return this.objectValue as List<JsonValue>;
}
/// <summary>
/// Use JsonValue as JsonArray and get JsonValue item by index.
/// </summary>
public JsonValue AsArrayGet(int index)
{
DebugTool.Assert(this.type == JsonType.Array, "JsonValue type is not Array !");
return (this.objectValue as List<JsonValue>)[index];
}
/// <summary>
/// Use JsonValue as JsonArray and get JsonObject item by index.
/// </summary>
public Dictionary<string, JsonValue> AsArrayGetObject(int index)
{
return this.AsArrayGet(index).AsObject();
}
/// <summary>
/// Use JsonValue as JsonArray and get JsonArray item by index.
/// </summary>
public List<JsonValue> AsArrayGetArray(int index)
{
return this.AsArrayGet(index).AsArray();
}
/// <summary>
/// Use JsonValue as JsonArray and get string item by index.
/// </summary>
public string AsArrayGetString(int index)
{
return this.AsArrayGet(index).AsString();
}
/// <summary>
/// Use JsonValue as JsonArray and get float item by index.
/// </summary>
public float AsArrayGetFloat(int index)
{
return this.AsArrayGet(index).AsFloat();
}
/// <summary>
/// Use JsonValue as JsonArray and get int item by index.
/// </summary>
public int AsArrayGetInt(int index)
{
return this.AsArrayGet(index).AsInt();
}
/// <summary>
/// Use JsonValue as JsonArray and get bool item by index.
/// </summary>
public bool AsArrayGetBool(int index)
{
return this.AsArrayGet(index).AsBool();
}
/// <summary>
/// Use JsonValue as JsonArray and check null item by index.
/// </summary>
public bool AsArrayGetIsNull(int index)
{
return this.AsArrayGet(index).IsNull();
}
#endregion
#region Other Json value API
/// <summary>
/// Get JsonValue as string.
/// </summary>
public string AsString()
{
DebugTool.Assert(this.type == JsonType.String, "JsonValue type is not String !");
return this.objectValue as string;
}
/// <summary>
/// Get JsonValue as float.
/// </summary>
public float AsFloat()
{
DebugTool.Assert(this.type == JsonType.Number, "JsonValue type is not Number !");
return this.numberValue;
}
/// <summary>
/// Get JsonValue as int.
/// </summary>
public int AsInt()
{
DebugTool.Assert(this.type == JsonType.Number, "JsonValue type is not Number !");
return (int) this.numberValue;
}
/// <summary>
/// Get JsonValue as bool.
/// </summary>
public bool AsBool()
{
DebugTool.Assert(this.type == JsonType.Bool, "JsonValue type is not Bool !");
return this.numberValue > 0.0f;
}
/// <summary>
/// Whether JsonValue is null ?
/// </summary>
public bool IsNull()
{
return this.type == JsonType.Null;
}
#endregion
}
internal static class DebugTool
{
public static void Assert(bool condition, string msg, params object[] args)
{
if (condition == false)
{
throw new Exception(string.Format(msg, args));
}
}
}
}