-
Notifications
You must be signed in to change notification settings - Fork 68
/
JSONObject.cs
1959 lines (1638 loc) · 49.2 KB
/
JSONObject.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
/*
Copyright (c) 2010-2021 Matt Schoen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
//#define JSONOBJECT_DISABLE_PRETTY_PRINT // Use when you no longer need to read JSON to disable pretty Print system-wide
//#define JSONOBJECT_USE_FLOAT //Use floats for numbers instead of doubles (enable if you don't need support for doubles and want to cut down on significant digits in output)
//#define JSONOBJECT_POOLING //Create JSONObjects from a pool and prevent finalization by returning objects to the pool
// ReSharper disable ArrangeAccessorOwnerBody
// ReSharper disable MergeConditionalExpression
// ReSharper disable UseStringInterpolation
#if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 || UNITY_5_3_OR_NEWER
#define USING_UNITY
#endif
using System;
using System.Diagnostics;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
#if USING_UNITY
using UnityEngine;
using Debug = UnityEngine.Debug;
#endif
namespace Defective.JSON {
public class JSONObject : IEnumerable {
#if JSONOBJECT_POOLING
const int MaxPoolSize = 100000;
static readonly Queue<JSONObject> JSONObjectPool = new Queue<JSONObject>();
static readonly Queue<List<JSONObject>> JSONObjectListPool = new Queue<List<JSONObject>>();
static readonly Queue<List<string>> StringListPool = new Queue<List<string>>();
static bool poolingEnabled = true;
#endif
#if !JSONOBJECT_DISABLE_PRETTY_PRINT
const string Newline = "\r\n";
const string Tab = "\t";
#endif
const string Infinity = "Infinity";
const string NegativeInfinity = "-Infinity";
const string NaN = "NaN";
const string True = "true";
const string False = "false";
const string Null = "null";
const float MaxFrameTime = 0.008f;
static readonly Stopwatch PrintWatch = new Stopwatch();
public static readonly char[] Whitespace = { ' ', '\r', '\n', '\t', '\uFEFF', '\u0009' };
public enum Type {
Null,
String,
Number,
Object,
Array,
Bool,
Baked
}
public struct ParseResult {
public readonly JSONObject result;
public readonly int offset;
public readonly bool pause;
public ParseResult(JSONObject result, int offset, bool pause) {
this.result = result;
this.offset = offset;
this.pause = pause;
}
}
public delegate void FieldNotFound(string name);
public delegate void GetFieldResponse(JSONObject jsonObject);
public Type type = Type.Null;
public List<JSONObject> list;
public List<string> keys;
public string stringValue;
public bool isInteger;
public long longValue;
public bool boolValue;
#if JSONOBJECT_USE_FLOAT
public float floatValue;
#else
public double doubleValue;
#endif
bool isPooled;
public int count {
get {
return list == null ? 0 : list.Count;
}
}
public bool isContainer {
get { return type == Type.Array || type == Type.Object; }
}
public int intValue {
get {
return (int) longValue;
}
set {
longValue = value;
}
}
#if JSONOBJECT_USE_FLOAT
public double doubleValue {
get {
return floatValue;
}
set {
floatValue = (float) value;
}
}
#else
public float floatValue {
get {
return (float) doubleValue;
}
set {
doubleValue = value;
}
}
#endif
public delegate void AddJSONContents(JSONObject self);
public static JSONObject nullObject {
get { return Create(Type.Null); }
}
public static JSONObject emptyObject {
get { return Create(Type.Object); }
}
public static JSONObject emptyArray {
get { return Create(Type.Array); }
}
public JSONObject(Type type) { this.type = type; }
public JSONObject(bool value) {
type = Type.Bool;
boolValue = value;
}
public JSONObject(float value) {
type = Type.Number;
#if JSONOBJECT_USE_FLOAT
floatValue = value;
#else
doubleValue = value;
#endif
}
public JSONObject(double value) {
type = Type.Number;
#if JSONOBJECT_USE_FLOAT
floatValue = (float)value;
#else
doubleValue = value;
#endif
}
public JSONObject(int value) {
type = Type.Number;
longValue = value;
isInteger = true;
#if JSONOBJECT_USE_FLOAT
floatValue = value;
#else
doubleValue = value;
#endif
}
public JSONObject(long value) {
type = Type.Number;
longValue = value;
isInteger = true;
#if JSONOBJECT_USE_FLOAT
floatValue = value;
#else
doubleValue = value;
#endif
}
public JSONObject(Dictionary<string, string> dictionary) {
type = Type.Object;
keys = CreateStringList();
list = CreateJSONObjectList();
foreach (KeyValuePair<string, string> kvp in dictionary) {
keys.Add(kvp.Key);
list.Add(CreateStringObject(kvp.Value));
}
}
public JSONObject(Dictionary<string, JSONObject> dictionary) {
type = Type.Object;
keys = CreateStringList();
list = CreateJSONObjectList();
foreach (KeyValuePair<string, JSONObject> kvp in dictionary) {
keys.Add(kvp.Key);
list.Add(kvp.Value);
}
}
public JSONObject(AddJSONContents content) {
content.Invoke(this);
}
public JSONObject(JSONObject[] objects) {
type = Type.Array;
list = CreateJSONObjectList();
list.AddRange(objects);
}
public JSONObject(List<JSONObject> objects) {
type = Type.Array;
list = objects;
}
/// <summary>
/// Convenience function for creating a JSONObject containing a string.
/// This is not part of the constructor so that malformed JSON data doesn't just turn into a string object
/// </summary>
/// <param name="value">The string value for the new JSONObject</param>
/// <returns>Thew new JSONObject</returns>
public static JSONObject StringObject(string value) {
return CreateStringObject(value);
}
public void Absorb(JSONObject other) {
var otherList = other.list;
if (otherList != null) {
if (list == null)
list = CreateJSONObjectList();
list.AddRange(otherList);
}
var otherKeys = other.keys;
if (otherKeys != null) {
if (keys == null)
keys = CreateStringList();
keys.AddRange(otherKeys);
}
stringValue = other.stringValue;
#if JSONOBJECT_USE_FLOAT
floatValue = other.floatValue;
#else
doubleValue = other.doubleValue;
#endif
isInteger = other.isInteger;
longValue = other.longValue;
boolValue = other.boolValue;
type = other.type;
}
public static JSONObject Create() {
#if JSONOBJECT_POOLING
lock (JSONObjectPool) {
if (JSONObjectPool.Count > 0) {
var result = JSONObjectPool.Dequeue();
result.isPooled = false;
return result;
}
}
#endif
return new JSONObject();
}
public static JSONObject Create(Type type) {
var jsonObject = Create();
jsonObject.type = type;
return jsonObject;
}
public static JSONObject Create(bool value) {
var jsonObject = Create();
jsonObject.type = Type.Bool;
jsonObject.boolValue = value;
return jsonObject;
}
public static JSONObject Create(float value) {
var jsonObject = Create();
jsonObject.type = Type.Number;
#if JSONOBJECT_USE_FLOAT
jsonObject.floatValue = value;
#else
jsonObject.doubleValue = value;
#endif
return jsonObject;
}
public static JSONObject Create(double value) {
var jsonObject = Create();
jsonObject.type = Type.Number;
#if JSONOBJECT_USE_FLOAT
jsonObject.floatValue = (float)value;
#else
jsonObject.doubleValue = value;
#endif
return jsonObject;
}
public static JSONObject Create(int value) {
var jsonObject = Create();
jsonObject.type = Type.Number;
jsonObject.isInteger = true;
jsonObject.longValue = value;
#if JSONOBJECT_USE_FLOAT
jsonObject.floatValue = value;
#else
jsonObject.doubleValue = value;
#endif
return jsonObject;
}
public static JSONObject Create(long value) {
var jsonObject = Create();
jsonObject.type = Type.Number;
jsonObject.isInteger = true;
jsonObject.longValue = value;
#if JSONOBJECT_USE_FLOAT
jsonObject.floatValue = value;
#else
jsonObject.doubleValue = value;
#endif
return jsonObject;
}
public static JSONObject CreateStringObject(string value) {
var jsonObject = Create();
jsonObject.type = Type.String;
jsonObject.stringValue = value;
return jsonObject;
}
public static JSONObject CreateBakedObject(string value) {
var bakedObject = Create();
bakedObject.type = Type.Baked;
bakedObject.stringValue = value;
return bakedObject;
}
/// <summary>
/// Create a JSONObject (using pooling if enabled) using a string containing valid JSON
/// </summary>
/// <param name="jsonString">A string containing valid JSON to be parsed into objects</param>
/// <param name="offset">An offset into the string at which to start parsing</param>
/// <param name="endOffset">The length of the string after the offset to parse
/// Specify a length of -1 (default) to use the full string length</param>
/// <param name="maxDepth">The maximum depth for the parser to search.</param>
/// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param>
/// <returns>A JSONObject containing the parsed data</returns>
public static JSONObject Create(string jsonString, int offset = 0, int endOffset = -1, int maxDepth = -1, bool storeExcessLevels = false) {
var jsonObject = Create();
Parse(jsonString, ref offset, endOffset, jsonObject, maxDepth, storeExcessLevels);
return jsonObject;
}
public static JSONObject Create(AddJSONContents content) {
var jsonObject = Create();
content.Invoke(jsonObject);
return jsonObject;
}
public static JSONObject Create(JSONObject[] objects) {
var jsonObject = Create();
jsonObject.type = Type.Array;
var list = CreateJSONObjectList();
list.AddRange(objects);
jsonObject.list = list;
return jsonObject;
}
public static JSONObject Create(List<JSONObject> objects) {
var jsonObject = Create();
jsonObject.type = Type.Array;
jsonObject.list = objects;
return jsonObject;
}
public static JSONObject Create(Dictionary<string, string> dictionary) {
var jsonObject = Create();
jsonObject.type = Type.Object;
var keys = CreateStringList();
jsonObject.keys = keys;
var list = CreateJSONObjectList();
jsonObject.list = list;
foreach (var kvp in dictionary) {
keys.Add(kvp.Key);
list.Add(CreateStringObject(kvp.Value));
}
return jsonObject;
}
public static JSONObject Create(Dictionary<string, JSONObject> dictionary) {
var jsonObject = Create();
jsonObject.type = Type.Object;
var keys = CreateStringList();
jsonObject.keys = keys;
var list = CreateJSONObjectList();
jsonObject.list = list;
foreach (var kvp in dictionary) {
keys.Add(kvp.Key);
list.Add(kvp.Value);
}
return jsonObject;
}
/// <summary>
/// Create a JSONObject (using pooling if enabled) using a string containing valid JSON
/// </summary>
/// <param name="jsonString">A string containing valid JSON to be parsed into objects</param>
/// <param name="offset">An offset into the string at which to start parsing</param>
/// <param name="endOffset">The length of the string after the offset to parse
/// Specify a length of -1 (default) to use the full string length</param>
/// <param name="maxDepth">The maximum depth for the parser to search.</param>
/// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param>
/// <returns>A JSONObject containing the parsed data</returns>
public static IEnumerable<ParseResult> CreateAsync(string jsonString, int offset = 0, int endOffset = -1, int maxDepth = -1, bool storeExcessLevels = false) {
var jsonObject = Create();
PrintWatch.Reset();
PrintWatch.Start();
foreach (var e in ParseAsync(jsonString, offset, endOffset, jsonObject, maxDepth, storeExcessLevels)) {
if (e.pause)
yield return e;
offset = e.offset;
}
yield return new ParseResult(jsonObject, offset, false);
}
public JSONObject() { }
/// <summary>
/// Construct a new JSONObject using a string containing valid JSON
/// </summary>
/// <param name="jsonString">A string containing valid JSON to be parsed into objects</param>
/// <param name="offset">An offset into the string at which to start parsing</param>
/// <param name="endOffset">The length of the string after the offset to parse
/// Specify a length of -1 (default) to use the full string length</param>
/// <param name="maxDepth">The maximum depth for the parser to search.</param>
/// <param name="storeExcessLevels">Whether to store levels beyond maxDepth in baked JSONObjects</param>
public JSONObject(string jsonString, int offset = 0, int endOffset = -1, int maxDepth = -1, bool storeExcessLevels = false) {
Parse(jsonString, ref offset, endOffset, this, maxDepth, storeExcessLevels);
}
// ReSharper disable UseNameofExpression
static bool BeginParse(string inputString, int offset, ref int endOffset, JSONObject container, int maxDepth, bool storeExcessLevels) {
if (container == null)
throw new ArgumentNullException("container");
if (maxDepth == 0) {
if (storeExcessLevels) {
container.stringValue = inputString;
container.type = Type.Baked;
} else {
container.type = Type.Null;
}
return false;
}
var stringLength = inputString.Length;
if (endOffset == -1)
endOffset = stringLength - 1;
if (string.IsNullOrEmpty(inputString)) {
return false;
}
if (endOffset >= stringLength)
throw new ArgumentException("Cannot parse if end offset is greater than or equal to string length", "endOffset");
if (offset > endOffset)
throw new ArgumentException("Cannot parse if offset is greater than end offset", "offset");
return true;
}
// ReSharper restore UseNameofExpression
static void Parse(string inputString, ref int offset, int endOffset, JSONObject container, int maxDepth,
bool storeExcessLevels, int depth = 0, bool isRoot = true) {
if (!BeginParse(inputString, offset, ref endOffset, container, maxDepth, storeExcessLevels))
return;
var startOffset = offset;
var quoteStart = 0;
var quoteEnd = 0;
var lastValidOffset = offset;
var openQuote = false;
var bakeDepth = 0;
while (offset <= endOffset) {
var currentCharacter = inputString[offset++];
if (Array.IndexOf(Whitespace, currentCharacter) > -1)
continue;
JSONObject newContainer;
switch (currentCharacter) {
case '\\':
offset++;
break;
case '{':
if (openQuote)
break;
if (maxDepth >= 0 && depth >= maxDepth) {
bakeDepth++;
break;
}
newContainer = container;
if (!isRoot) {
newContainer = Create();
SafeAddChild(container, newContainer);
}
newContainer.type = Type.Object;
Parse(inputString, ref offset, endOffset, newContainer, maxDepth, storeExcessLevels, depth + 1, false);
break;
case '[':
if (openQuote)
break;
if (maxDepth >= 0 && depth >= maxDepth) {
bakeDepth++;
break;
}
newContainer = container;
if (!isRoot) {
newContainer = Create();
SafeAddChild(container, newContainer);
}
newContainer.type = Type.Array;
Parse(inputString, ref offset, endOffset, newContainer, maxDepth, storeExcessLevels, depth + 1, false);
break;
case '}':
if (!ParseObjectEnd(inputString, offset, openQuote, container, startOffset, lastValidOffset, maxDepth, storeExcessLevels, depth, ref bakeDepth))
return;
break;
case ']':
if (!ParseArrayEnd(inputString, offset, openQuote, container, startOffset, lastValidOffset, maxDepth, storeExcessLevels, depth, ref bakeDepth))
return;
break;
case '"':
ParseQuote(ref openQuote, offset, ref quoteStart, ref quoteEnd);
break;
case ':':
if (!ParseColon(inputString, openQuote, container, ref startOffset, offset, quoteStart, quoteEnd, bakeDepth))
return;
break;
case ',':
if (!ParseComma(inputString, openQuote, container, ref startOffset, offset, lastValidOffset, bakeDepth))
return;
break;
}
lastValidOffset = offset - 1;
}
}
static IEnumerable<ParseResult> ParseAsync(string inputString, int offset, int endOffset, JSONObject container,
int maxDepth, bool storeExcessLevels, int depth = 0, bool isRoot = true) {
if (!BeginParse(inputString, offset, ref endOffset, container, maxDepth, storeExcessLevels))
yield break;
var startOffset = offset;
var quoteStart = 0;
var quoteEnd = 0;
var lastValidOffset = offset;
var openQuote = false;
var bakeDepth = 0;
while (offset <= endOffset) {
if (PrintWatch.Elapsed.TotalSeconds > MaxFrameTime) {
PrintWatch.Reset();
yield return new ParseResult(container, offset, true);
PrintWatch.Start();
}
var currentCharacter = inputString[offset++];
if (Array.IndexOf(Whitespace, currentCharacter) > -1)
continue;
JSONObject newContainer;
switch (currentCharacter) {
case '\\':
offset++;
break;
case '{':
if (openQuote)
break;
if (maxDepth >= 0 && depth >= maxDepth) {
bakeDepth++;
break;
}
newContainer = container;
if (!isRoot) {
newContainer = Create();
SafeAddChild(container, newContainer);
}
newContainer.type = Type.Object;
foreach (var e in ParseAsync(inputString, offset, endOffset, newContainer, maxDepth, storeExcessLevels, depth + 1, false)) {
if (e.pause)
yield return e;
offset = e.offset;
}
break;
case '[':
if (openQuote)
break;
if (maxDepth >= 0 && depth >= maxDepth) {
bakeDepth++;
break;
}
newContainer = container;
if (!isRoot) {
newContainer = Create();
SafeAddChild(container, newContainer);
}
newContainer.type = Type.Array;
foreach (var e in ParseAsync(inputString, offset, endOffset, newContainer, maxDepth, storeExcessLevels, depth + 1, false)) {
if (e.pause)
yield return e;
offset = e.offset;
}
break;
case '}':
if (!ParseObjectEnd(inputString, offset, openQuote, container, startOffset, lastValidOffset, maxDepth, storeExcessLevels, depth, ref bakeDepth)) {
yield return new ParseResult(container, offset, false);
yield break;
}
break;
case ']':
if (!ParseArrayEnd(inputString, offset, openQuote, container, startOffset, lastValidOffset, maxDepth, storeExcessLevels, depth, ref bakeDepth)) {
yield return new ParseResult(container, offset, false);
yield break;
}
break;
case '"':
ParseQuote(ref openQuote, offset, ref quoteStart, ref quoteEnd);
break;
case ':':
if (!ParseColon(inputString, openQuote, container, ref startOffset, offset, quoteStart, quoteEnd, bakeDepth)) {
yield return new ParseResult(container, offset, false);
yield break;
}
break;
case ',':
if (!ParseComma(inputString, openQuote, container, ref startOffset, offset, lastValidOffset, bakeDepth)) {
yield return new ParseResult(container, offset, false);
yield break;
}
break;
}
lastValidOffset = offset - 1;
}
yield return new ParseResult(container, offset, false);
}
static void SafeAddChild(JSONObject container, JSONObject child) {
var list = container.list;
if (list == null) {
list = CreateJSONObjectList();
container.list = list;
}
list.Add(child);
}
void ParseValue(string inputString, int startOffset, int lastValidOffset) {
var firstCharacter = inputString[startOffset];
do {
if (Array.IndexOf(Whitespace, firstCharacter) > -1) {
firstCharacter = inputString[++startOffset];
continue;
}
break;
} while (true);
// Use character comparison instead of string compare as performance optimization
switch (firstCharacter)
{
case '"':
type = Type.String;
// Trim quotes from string values
stringValue = UnEscapeString(inputString.Substring(startOffset + 1, lastValidOffset - startOffset - 1));
return;
case 't':
type = Type.Bool;
boolValue = true;
return;
case 'f':
type = Type.Bool;
boolValue = false;
return;
case 'n':
type = Type.Null;
return;
case 'I':
type = Type.Number;
#if JSONOBJECT_USE_FLOAT
floatValue = float.PositiveInfinity;
#else
doubleValue = double.PositiveInfinity;
#endif
return;
case 'N':
type = Type.Number;
#if JSONOBJECT_USE_FLOAT
floatValue = float.NaN;
#else
doubleValue = double.NaN;
#endif
return;
case '-':
if (inputString[startOffset + 1] == 'I') {
type = Type.Number;
#if JSONOBJECT_USE_FLOAT
floatValue = float.NegativeInfinity;
#else
doubleValue = double.NegativeInfinity;
#endif
return;
}
break;
}
var numericString = inputString.Substring(startOffset, lastValidOffset - startOffset + 1);
try {
if (numericString.Contains(".")) {
#if JSONOBJECT_USE_FLOAT
floatValue = Convert.ToSingle(numericString, CultureInfo.InvariantCulture);
#else
doubleValue = Convert.ToDouble(numericString, CultureInfo.InvariantCulture);
#endif
} else {
longValue = Convert.ToInt64(numericString, CultureInfo.InvariantCulture);
isInteger = true;
#if JSONOBJECT_USE_FLOAT
floatValue = longValue;
#else
doubleValue = longValue;
#endif
}
type = Type.Number;
} catch (OverflowException) {
type = Type.Number;
#if JSONOBJECT_USE_FLOAT
floatValue = numericString.StartsWith("-") ? float.NegativeInfinity : float.PositiveInfinity;
#else
doubleValue = numericString.StartsWith("-") ? double.NegativeInfinity : double.PositiveInfinity;
#endif
} catch (FormatException) {
type = Type.Null;
#if USING_UNITY
Debug.LogWarning
#else
Debug.WriteLine
#endif
(string.Format("Improper JSON formatting:{0}", numericString));
}
}
static bool ParseObjectEnd(string inputString, int offset, bool openQuote, JSONObject container, int startOffset,
int lastValidOffset, int maxDepth, bool storeExcessLevels, int depth, ref int bakeDepth) {
if (openQuote)
return true;
if (container == null) {
Debug.LogError("Parsing error: encountered `}` with no container object");
return false;
}
if (maxDepth >= 0 && depth >= maxDepth) {
bakeDepth--;
if (bakeDepth == 0) {
SafeAddChild(container,
storeExcessLevels
? CreateBakedObject(inputString.Substring(startOffset, offset - startOffset))
: nullObject);
}
if (bakeDepth >= 0)
return true;
}
ParseFinalObjectIfNeeded(inputString, container, startOffset, lastValidOffset);
return false;
}
static bool ParseArrayEnd(string inputString, int offset, bool openQuote, JSONObject container,
int startOffset, int lastValidOffset, int maxDepth, bool storeExcessLevels, int depth, ref int bakeDepth) {
if (openQuote)
return true;
if (container == null) {
Debug.LogError("Parsing error: encountered `]` with no container object");
return false;
}
if (maxDepth >= 0 && depth >= maxDepth) {
bakeDepth--;
if (bakeDepth == 0) {
SafeAddChild(container,
storeExcessLevels
? CreateBakedObject(inputString.Substring(startOffset, offset - startOffset))
: nullObject);
}
if (bakeDepth >= 0)
return true;
}
ParseFinalObjectIfNeeded(inputString, container, startOffset, lastValidOffset);
return false;
}
static void ParseQuote(ref bool openQuote, int offset, ref int quoteStart, ref int quoteEnd) {
if (openQuote) {
quoteEnd = offset - 1;
openQuote = false;
} else {
quoteStart = offset;
openQuote = true;
}
}
static bool ParseColon(string inputString, bool openQuote, JSONObject container,
ref int startOffset,int offset, int quoteStart, int quoteEnd, int bakeDepth) {
if (openQuote || bakeDepth > 0)
return true;
if (container == null) {
Debug.LogError("Parsing error: encountered `:` with no container object");
return false;
}
var keys = container.keys;
if (keys == null) {
keys = CreateStringList();
container.keys = keys;
}
container.keys.Add(inputString.Substring(quoteStart, quoteEnd - quoteStart));
startOffset = offset;
return true;
}
static bool ParseComma(string inputString, bool openQuote, JSONObject container,
ref int startOffset, int offset, int lastValidOffset, int bakeDepth) {
if (openQuote || bakeDepth > 0)
return true;
if (container == null) {
Debug.LogError("Parsing error: encountered `,` with no container object");
return false;
}
ParseFinalObjectIfNeeded(inputString, container, startOffset, lastValidOffset);
startOffset = offset;
return true;
}
static void ParseFinalObjectIfNeeded(string inputString, JSONObject container, int startOffset, int lastValidOffset) {
if (IsClosingCharacter(inputString[lastValidOffset]))
return;
var child = Create();
child.ParseValue(inputString, startOffset, lastValidOffset);
SafeAddChild(container, child);
}
static bool IsClosingCharacter(char character) {
switch (character) {
case '}':
case ']':
return true;
}
return false;
}
public bool isNumber {
get { return type == Type.Number; }
}
public bool isNull {
get { return type == Type.Null; }
}
public bool isString {
get { return type == Type.String; }
}
public bool isBool {
get { return type == Type.Bool; }
}
public bool isArray {
get { return type == Type.Array; }
}
public bool isObject {
get { return type == Type.Object; }
}
public bool isBaked {
get { return type == Type.Baked; }
}
public void Add(bool value) {
Add(Create(value));
}
public void Add(float value) {
Add(Create(value));
}
public void Add(double value) {
Add(Create(value));
}