-
Notifications
You must be signed in to change notification settings - Fork 86
/
JsonDataObjects.pas
7890 lines (7190 loc) · 214 KB
/
JsonDataObjects.pas
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
(*****************************************************************************
The MIT License (MIT)
Copyright (c) 2015-2016 Andreas Hausladen
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.
*****************************************************************************)
{$A8,B-,C+,E-,F-,G+,H+,I+,J-,K-,M-,N-,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Z1}
{$WARN WIDECHAR_REDUCED OFF} // All sets only use ASCII chars (<=#127) and the compiler generates the >=#128 check itself
{$STRINGCHECKS OFF} // It only slows down Delphi strings, doesn't help C++Builder migration and is finally gone in XE+
{$WARN SYMBOL_DEPRECATED OFF} // for StrLen/StrLComp
{$POINTERMATH ON}
unit JsonDataObjects;
{$IFDEF VER200}
// Delphi 2009's ErrorInsight parser uses the CompilerVersion's memory address instead of 20.0, failing all the
// IF CompilerVersion compiler directives
{$DEFINE CPUX86}
{$ELSE}
{$IF CompilerVersion >= 24.0} // XE3 or newer
{$LEGACYIFEND ON}
{$IFEND}
{$IF CompilerVersion >= 23.0}
{$DEFINE HAS_UNIT_SCOPE}
{$DEFINE HAS_RETURN_ADDRESS}
{$IFEND}
{$IF CompilerVersion <= 22.0} // XE or older
{$DEFINE CPUX86}
{$IFEND}
{$ENDIF VER200}
{$IFDEF NEXTGEN}
{$IF CompilerVersion >= 31.0} // 10.1 Berlin or newer
{$DEFINE SUPPORTS_UTF8STRING} // Delphi 10.1 Berlin supports UTF8String for mobile compilers
{$IFEND}
{$ELSE}
{$DEFINE SUPPORTS_UTF8STRING}
{$ENDIF}
// Enables the progress callback feature
{$DEFINE SUPPORT_PROGRESS}
// Sanity checks all array index accesses and raise an EListError exception.
{$DEFINE CHECK_ARRAY_INDEX}
// JSON allows the slash to be escaped. This is only necessary if you plan to put the JSON string
// into a <script>-Tag because then "</" can't be used and must be escaped to "<\/". This switch
// enables the special handling for "</" but makes the parser slightly slower.
{.$DEFINE ESCAPE_SLASH_AFTER_LESSTHAN}
// When parsing a JSON string the pair names are interned to reduce the memory foot print. This
// slightly slows down the parser but saves a lot of memory if the JSON string contains repeating
// pair names. The interning uses a hashset to store the strings.
{$DEFINE USE_STRINGINTERN_FOR_NAMES}
// Use an optimized NewInstance implementation. It skips the initialization of the interface table.
// and seals the TJsonArray and TJsonObject classes because it isn't safe to derive from them.
{$DEFINE USE_FAST_NEWINSTANCE}
//{$IF CompilerVersion < 28.0} // XE6 or older
// The XE7 compiler is broken. It doesn't collapse duplicate string literals anymore. (RSP-10015)
// But if the string literals are used in loops this optimization still helps.
// Optimizes the following pattern:
// O['Name'][MyPropStr]
// O['Name']['MyProp'].
// where the second O['Name'] is handled very fast by caching the pointer to the 'Name' string literal.
{$DEFINE USE_LAST_NAME_STRING_LITERAL_CACHE}
//{$IFEND}
// When parsing the JSON string, the UStrAsg calls are skipped for internal strings what eliminates
// the CPU locks for those string assignments.
{$DEFINE USE_FAST_STRASG_FOR_INTERNAL_STRINGS}
{$IFDEF AUTOREFCOUNT}
// Delphi's ARC is slow (RSP-9712). This switch enables a faster ARC handling and even skips memory
// barrier were possible.
{$DEFINE USE_FAST_AUTOREFCOUNT}
{$ENDIF AUTOREFCOUNT}
{$IFDEF MSWINDOWS}
// When adding JSON object properties with string literals, the string literals are stored directly
// in the "Name" field instead of using UStrAsg that creates a new heap string. This improves the
// performance as no string is copied and it slighly reduces the memory usage.
// The string literals are only used if they are in the main instance or the DLL that contains the
// JsonDataObjects unit. Other string literals are copied using UStrAsg because unloading the DLL
// that holds them would cause access violations.
// This has no effect when parsing JSON strings because then there are no string literals.
{$DEFINE USE_NAME_STRING_LITERAL}
// Reading a large file >64 MB from a network drive in Windows 2003 Server or older can lead to
// an INSUFFICIENT RESOURCES error. By enabling this switch, large files are read in 20 MB blocks.
{$DEFINE WORKAROUND_NETWORK_FILE_INSUFFICIENT_RESOURCES}
// If defined, the TzSpecificLocalTimeToSystemTime is imported with GetProcAddress and if it is
// not available (Windows 2000) an alternative implementation is used.
{$DEFINE SUPPORT_WINDOWS2000}
{$ENDIF MSWINDOWS}
interface
uses
{$IFDEF HAS_UNIT_SCOPE}
System.SysUtils, System.Classes;
{$ELSE}
SysUtils, Classes;
{$ENDIF HAS_UNIT_SCOPE}
type
TJsonBaseObject = class;
TJsonObject = class;
TJsonArray = class;
{$IFDEF NEXTGEN}
// Mobile compilers have PAnsiChar but it is hidden and then published under a new name. This alias
// allows us to remove some IFDEFs.
PAnsiChar = MarshaledAString;
{$ENDIF NEXTGEN}
EJsonException = class(Exception);
EJsonCastException = class(EJsonException);
EJsonPathException = class(EJsonException);
EJsonParserException = class(EJsonException)
private
FColumn: NativeInt;
FPosition: NativeInt;
FLineNum: NativeInt;
public
constructor CreateResFmt(ResStringRec: PResStringRec; const Args: array of const; ALineNum, AColumn, APosition: NativeInt);
constructor CreateRes(ResStringRec: PResStringRec; ALineNum, AColumn, APosition: NativeInt);
property LineNum: NativeInt read FLineNum; // base 1
property Column: NativeInt read FColumn; // base 1
property Position: NativeInt read FPosition; // base 0 Utf8Char/WideChar index
end;
{$IFDEF SUPPORT_PROGRESS}
TJsonReaderProgressProc = procedure(Data: Pointer; Percentage: Integer; Position, Size: NativeInt);
PJsonReaderProgressRec = ^TJsonReaderProgressRec;
TJsonReaderProgressRec = record
Data: Pointer; // used for the first Progress() parameter
Threshold: NativeInt; // 0: Call only if percentage changed; greater than 0: call after n processed bytes
Progress: TJsonReaderProgressProc;
function Init(AProgress: TJsonReaderProgressProc; AData: Pointer = nil; AThreshold: NativeInt = 0): PJsonReaderProgressRec;
end;
{$ENDIF SUPPORT_PROGRESS}
// TJsonOutputWriter is used to write the JSON data to a string, stream or TStrings in a compact
// or human readable format.
TJsonOutputWriter = record
private type
TLastType = (ltInitial, ltIndent, ltUnindent, ltIntro, ltValue, ltSeparator);
PJsonStringArray = ^TJsonStringArray;
TJsonStringArray = array[0..MaxInt div SizeOf(string) - 1] of string;
PJsonStringBuilder = ^TJsonStringBuilder;
TJsonStringBuilder = record
private
FData: PChar;
FCapacity: Integer;
FLen: Integer;
procedure Grow(MinLen: Integer);
public
procedure Init;
procedure Done;
procedure DoneConvertToString(var S: string);
function FlushToBytes(var Bytes: PByte; var Size: NativeInt; Encoding: TEncoding): NativeInt;
procedure FlushToMemoryStream(Stream: TMemoryStream; Encoding: TEncoding);
procedure FlushToStringBuffer(var Buffer: TJsonStringBuilder);
procedure FlushToString(var S: string);
function Append(const S: string): PJsonStringBuilder; overload;
procedure Append(P: PChar; Len: Integer); overload;
function Append2(const S1: string; S2: PChar; S2Len: Integer): PJsonStringBuilder; overload;
procedure Append2(Ch1: Char; Ch2: Char); overload;
procedure Append3(Ch1: Char; const S2, S3: string); overload;
procedure Append3(Ch1: Char; const S2: string; Ch3: Char); overload; inline;
procedure Append3(Ch1: Char; const P2: PChar; P2Len: Integer; Ch3: Char); overload;
property Len: Integer read FLen;
property Data: PChar read FData;
end;
private
FLastType: TLastType;
FCompact: Boolean;
FStringBuffer: TJsonStringBuilder;
FLines: TStrings;
FLastLine: TJsonStringBuilder;
FStreamEncodingBuffer: PByte;
FStreamEncodingBufferLen: NativeInt;
FStream: TStream; // used when writing to a stream
FEncoding: TEncoding; // used when writing to a stream
FIndents: PJsonStringArray; // buffer for line indention strings
FIndentsLen: Integer;
FIndent: Integer; // current indention level
procedure StreamFlushPossible; inline; // checks if StreamFlush must be called
procedure StreamFlush; // writes the buffer to the stream
procedure ExpandIndents;
procedure AppendLine(AppendOn: TLastType; const S: string); overload; inline;
procedure AppendLine(AppendOn: TLastType; P: PChar; Len: Integer); overload; inline;
procedure FlushLastLine;
private // unit private
procedure Init(ACompact: Boolean; AStream: TStream; AEncoding: TEncoding; ALines: TStrings);
function Done: string;
procedure StreamDone;
procedure LinesDone;
procedure Indent(const S: string);
procedure Unindent(const S: string);
procedure AppendIntro(P: PChar; Len: Integer);
procedure AppendValue(const S: string); overload;
procedure AppendValue(P: PChar; Len: Integer); overload;
procedure AppendStrValue(P: PChar; Len: Integer);
procedure AppendSeparator(const S: string);
procedure FreeIndents;
end;
TJsonDataType = (
jdtNone, jdtString, jdtInt, jdtLong, jdtULong, jdtFloat, jdtDateTime, jdtBool, jdtArray, jdtObject
);
// TJsonDataValue holds the actual value
PJsonDataValue = ^TJsonDataValue;
TJsonDataValue = packed record
private type
TJsonDataValueRec = record
case TJsonDataType of
jdtNone: (P: PChar); // helps when debugging
jdtString: (S: Pointer); // We manage the string ourself. Delphi doesn't allow "string" in a
// variant record and if we have no string, we don't need to clean
// it up, anyway.
jdtInt: (I: Integer);
jdtLong: (L: Int64);
jdtULong: (U: UInt64);
jdtFloat: (F: Double);
jdtDateTime: (D: TDateTime);
jdtBool: (B: Boolean);
jdtArray: (A: Pointer); // owned by TJsonDataValue
jdtObject: (O: Pointer); // owned by TJsonDataValue
end;
private
FValue: TJsonDataValueRec;
FTyp: TJsonDataType;
function GetValue: string;
function GetIntValue: Integer;
function GetLongValue: Int64;
function GetULongValue: UInt64;
function GetFloatValue: Double;
function GetDateTimeValue: TDateTime;
function GetBoolValue: Boolean;
function GetArrayValue: TJsonArray;
function GetObjectValue: TJsonObject;
function GetVariantValue: Variant;
procedure SetValue(const AValue: string);
procedure SetIntValue(const AValue: Integer);
procedure SetLongValue(const AValue: Int64);
procedure SetULongValue(const AValue: UInt64);
procedure SetFloatValue(const AValue: Double);
procedure SetDateTimeValue(const AValue: TDateTime);
procedure SetBoolValue(const AValue: Boolean);
procedure SetArrayValue(const AValue: TJsonArray);
procedure SetObjectValue(const AValue: TJsonObject);
procedure SetVariantValue(const AValue: Variant);
procedure InternToJSON(var Writer: TJsonOutputWriter);
procedure InternSetValue(const AValue: string); // skips the call to Clear()
procedure InternSetValueTransfer(var AValue: string); // skips the call to Clear() and transfers the string without going through UStrAsg+UStrClr
procedure InternSetArrayValue(const AValue: TJsonArray);
procedure InternSetObjectValue(const AValue: TJsonObject);
procedure Clear;
procedure TypeCastError(ExpectedType: TJsonDataType);
public
property Typ: TJsonDataType read FTyp;
property Value: string read GetValue write SetValue;
property IntValue: Integer read GetIntValue write SetIntValue;
property LongValue: Int64 read GetLongValue write SetLongValue;
property ULongValue: UInt64 read GetULongValue write SetULongValue;
property FloatValue: Double read GetFloatValue write SetFloatValue;
property DateTimeValue: TDateTime read GetDateTimeValue write SetDateTimeValue;
property BoolValue: Boolean read GetBoolValue write SetBoolValue;
property ArrayValue: TJsonArray read GetArrayValue write SetArrayValue;
property ObjectValue: TJsonObject read GetObjectValue write SetObjectValue;
property VariantValue: Variant read GetVariantValue write SetVariantValue;
end;
// TJsonDataValueHelper is used to implement the "easy access" functionality. It is
// slightly slower than using the direct indexed properties.
TJsonDataValueHelper = record
private
function GetValue: string; inline;
function GetIntValue: Integer; inline;
function GetLongValue: Int64; inline;
function GetULongValue: UInt64; //inline; no implicit operator due to conflict with Int64
function GetFloatValue: Double; inline;
function GetDateTimeValue: TDateTime; inline;
function GetBoolValue: Boolean; inline;
function GetArrayValue: TJsonArray; inline;
function GetObjectValue: TJsonObject; inline;
function GetVariantValue: Variant; inline;
procedure SetValue(const Value: string);
procedure SetIntValue(const Value: Integer);
procedure SetLongValue(const Value: Int64);
procedure SetULongValue(const Value: UInt64);
procedure SetFloatValue(const Value: Double);
procedure SetDateTimeValue(const Value: TDateTime);
procedure SetBoolValue(const Value: Boolean);
procedure SetArrayValue(const Value: TJsonArray);
procedure SetObjectValue(const Value: TJsonObject);
procedure SetVariantValue(const Value: Variant);
function GetArrayItem(Index: Integer): TJsonDataValueHelper; inline;
function GetArrayCount: Integer; inline;
function GetObjectString(const Name: string): string; inline;
function GetObjectInt(const Name: string): Integer; inline;
function GetObjectLong(const Name: string): Int64; inline;
function GetObjectULong(const Name: string): UInt64; inline;
function GetObjectFloat(const Name: string): Double; inline;
function GetObjectDateTime(const Name: string): TDateTime; inline;
function GetObjectBool(const Name: string): Boolean; inline;
function GetArray(const Name: string): TJsonArray; inline;
function GetObject(const Name: string): TJsonDataValueHelper; inline;
function GetObjectVariant(const Name: string): Variant; inline;
procedure SetObjectString(const Name, Value: string); inline;
procedure SetObjectInt(const Name: string; const Value: Integer); inline;
procedure SetObjectLong(const Name: string; const Value: Int64); inline;
procedure SetObjectULong(const Name: string; const Value: UInt64); inline;
procedure SetObjectFloat(const Name: string; const Value: Double); inline;
procedure SetObjectDateTime(const Name: string; const Value: TDateTime); inline;
procedure SetObjectBool(const Name: string; const Value: Boolean); inline;
procedure SetArray(const Name: string; const Value: TJsonArray); inline;
procedure SetObject(const Name: string; const Value: TJsonDataValueHelper); inline;
procedure SetObjectVariant(const Name: string; const Value: Variant); inline;
function GetObjectPath(const Name: string): TJsonDataValueHelper; inline;
procedure SetObjectPath(const Name: string; const Value: TJsonDataValueHelper); inline;
function GetTyp: TJsonDataType;
procedure ResolveName;
class procedure SetInternValue(Item: PJsonDataValue; const Value: TJsonDataValueHelper); static;
public
class operator Implicit(const Value: string): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): string; overload;
class operator Implicit(const Value: Integer): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): Integer; overload;
class operator Implicit(const Value: Int64): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): Int64; overload;
//class operator Implicit(const Value: UInt64): TJsonDataValueHelper; overload; conflicts with Int64 operator
//class operator Implicit(const Value: TJsonDataValueHelper): UInt64; overload; conflicts with Int64 operator
class operator Implicit(const Value: Double): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): Double; overload;
class operator Implicit(const Value: Extended): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): Extended; overload;
class operator Implicit(const Value: TDateTime): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): TDateTime; overload;
class operator Implicit(const Value: Boolean): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): Boolean; overload;
class operator Implicit(const Value: TJsonArray): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): TJsonArray; overload;
class operator Implicit(const Value: TJsonObject): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): TJsonObject; overload;
class operator Implicit(const Value: Pointer): TJsonDataValueHelper; overload;
class operator Implicit(const Value: TJsonDataValueHelper): Variant; overload;
class operator Implicit(const Value: Variant): TJsonDataValueHelper; overload;
property Typ: TJsonDataType read GetTyp;
property Value: string read GetValue write SetValue;
property IntValue: Integer read GetIntValue write SetIntValue;
property LongValue: Int64 read GetLongValue write SetLongValue;
property ULongValue: UInt64 read GetULongValue write SetULongValue;
property FloatValue: Double read GetFloatValue write SetFloatValue;
property DateTimeValue: TDateTime read GetDateTimeValue write SetDateTimeValue;
property BoolValue: Boolean read GetBoolValue write SetBoolValue;
property ArrayValue: TJsonArray read GetArrayValue write SetArrayValue;
property ObjectValue: TJsonObject read GetObjectValue write SetObjectValue;
property VariantValue: Variant read GetVariantValue write SetVariantValue;
// Access to array item count
property Count: Integer read GetArrayCount;
// Access to array items
property Items[Index: Integer]: TJsonDataValueHelper read GetArrayItem;
property S[const Name: string]: string read GetObjectString write SetObjectString; // returns '' if property doesn't exist, auto type-cast except for array/object
property I[const Name: string]: Integer read GetObjectInt write SetObjectInt; // returns 0 if property doesn't exist, auto type-cast except for array/object
property L[const Name: string]: Int64 read GetObjectLong write SetObjectLong; // returns 0 if property doesn't exist, auto type-cast except for array/object
property U[const Name: string]: UInt64 read GetObjectULong write SetObjectULong; // returns 0 if property doesn't exist, auto type-cast except for array/object
property F[const Name: string]: Double read GetObjectFloat write SetObjectFloat; // returns 0 if property doesn't exist, auto type-cast except for array/object
property D[const Name: string]: TDateTime read GetObjectDateTime write SetObjectDateTime; // returns 0 if property doesn't exist, auto type-cast except for array/object
property B[const Name: string]: Boolean read GetObjectBool write SetObjectBool; // returns false if property doesn't exist, auto type-cast with "<>'true'" and "<>0" except for array/object
// Used to auto create arrays
property A[const Name: string]: TJsonArray read GetArray write SetArray;
// Used to auto create objects and as default property where no Implicit operator matches
property O[const Name: string]: TJsonDataValueHelper read GetObject write SetObject; default;
property V[const Name: string]: Variant read GetObjectVariant write SetObjectVariant;
property Path[const Name: string]: TJsonDataValueHelper read GetObjectPath write SetObjectPath;
private
FData: record // hide the data from CodeInsight (bug in CodeInsight)
FIntern: PJsonDataValue;
FName: string;
FNameResolver: TJsonObject;
FValue: string; // must be managed by Delphi otherwise we have a memory leak
{$IFDEF AUTOREFCOUNT}
FObj: TJsonBaseObject;
{$ENDIF AUTOREFCOUNT}
case FTyp: TJsonDataType of
jdtInt: (FIntValue: Integer);
jdtLong: (FLongValue: Int64);
jdtULong: (FULongValue: UInt64);
jdtFloat: (FFloatValue: Double);
jdtDateTime: (FDateTimeValue: TDateTime);
jdtBool: (FBoolValue: Boolean);
{$IFNDEF AUTOREFCOUNT}
jdtObject: (FObj: TJsonBaseObject); // used for both Array and Object
//jdtArray: (FArrayValue: TJsonArray);
//jdtObject: (FObjectValue: TJsonObject);
{$ENDIF AUTOREFCOUNT}
end;
end;
// TJsonBaseObject is the base class for TJsonArray and TJsonObject
TJsonBaseObject = class abstract(TObject)
private type
TWriterAppendMethod = procedure(P: PChar; Len: Integer) of object;
TStreamInfo = record
Buffer: PByte;
Size: NativeInt;
AllocationBase: Pointer;
end;
private
class procedure StrToJSONStr(const AppendMethod: TWriterAppendMethod; const S: string); static;
class procedure EscapeStrToJSONStr(F, P, EndP: PChar; const AppendMethod: TWriterAppendMethod); static;
class procedure DateTimeToJSONStr(const AppendMethod: TWriterAppendMethod;
const Value: TDateTime); static;
class procedure InternInitAndAssignItem(Dest, Source: PJsonDataValue); static;
class procedure GetStreamBytes(Stream: TStream; var Encoding: TEncoding; Utf8WithoutBOM: Boolean;
var StreamInfo: TStreamInfo); static;
{$IFDEF USE_FAST_AUTOREFCOUNT}
function ARCObjRelease: Integer; inline;
function ARCObjAddRef: Integer; inline;
{$ENDIF USE_FAST_AUTOREFCOUNT}
protected
procedure InternToJSON(var Writer: TJsonOutputWriter); virtual; abstract;
public
const DataTypeNames: array[TJsonDataType] of string = (
'null', 'String', 'Integer', 'Long', 'ULong', 'Float', 'DateTime', 'Bool', 'Array', 'Object'
);
{$IFDEF USE_FAST_NEWINSTANCE}
class function NewInstance: TObject {$IFDEF AUTOREFCOUNT} unsafe {$ENDIF}; override;
{$ENDIF USE_FAST_NEWINSTANCE}
// ParseXxx returns nil if the JSON string is empty or consists only of white chars.
// If the JSON string starts with a "[" then the returned object is a TJsonArray otherwise
// it is a TJsonObject.
class function ParseUtf8(S: PAnsiChar; Len: Integer = -1{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}): TJsonBaseObject; overload; static; inline;
{$IFDEF SUPPORTS_UTF8STRING}
class function ParseUtf8(const S: UTF8String{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}): TJsonBaseObject; overload; static; inline;
{$ENDIF SUPPORTS_UTF8STRING}
class function ParseUtf8Bytes(S: PByte; Len: Integer = -1{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}): TJsonBaseObject; static;
class function Parse(S: PWideChar; Len: Integer = -1{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}): TJsonBaseObject; overload; static;
class function Parse(const S: UnicodeString{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}): TJsonBaseObject; overload; static; inline;
class function Parse(const Bytes: TBytes; Encoding: TEncoding = nil; ByteIndex: Integer = 0;
ByteCount: Integer = -1{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}): TJsonBaseObject; overload; static;
class function ParseFromFile(const FileName: string; Utf8WithoutBOM: Boolean = True{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}): TJsonBaseObject; static;
class function ParseFromStream(Stream: TStream; Encoding: TEncoding = nil; Utf8WithoutBOM: Boolean = True{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}): TJsonBaseObject; static;
procedure LoadFromFile(const FileName: string; Utf8WithoutBOM: Boolean = True{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF});
procedure LoadFromStream(Stream: TStream; Encoding: TEncoding = nil; Utf8WithoutBOM: Boolean = True{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF});
procedure SaveToFile(const FileName: string; Compact: Boolean = True; Encoding: TEncoding = nil; Utf8WithoutBOM: Boolean = True);
procedure SaveToStream(Stream: TStream; Compact: Boolean = True; Encoding: TEncoding = nil; Utf8WithoutBOM: Boolean = True);
procedure SaveToLines(Lines: TStrings);
// FromXxxJSON() raises an EJsonParserException if you try to parse an array JSON string into a
// TJsonObject or a object JSON string into a TJsonArray.
{$IFDEF SUPPORTS_UTF8STRING}
procedure FromUtf8JSON(const S: UTF8String{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}); overload; inline;
{$ENDIF SUPPORTS_UTF8STRING}
procedure FromUtf8JSON(S: PAnsiChar; Len: Integer = -1{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}); overload; inline;
procedure FromUtf8JSON(S: PByte; Len: Integer = -1{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}); overload;
procedure FromJSON(const S: UnicodeString{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}); overload;
procedure FromJSON(S: PWideChar; Len: Integer = -1{$IFDEF SUPPORT_PROGRESS}; AProgress: PJsonReaderProgressRec = nil{$ENDIF}); overload;
function ToJSON(Compact: Boolean = True): string;
{$IFDEF SUPPORTS_UTF8STRING}
function ToUtf8JSON(Compact: Boolean = True): UTF8String; overload;
{$ENDIF SUPPORTS_UTF8STRING}
procedure ToUtf8JSON(var Bytes: TBytes; Compact: Boolean = True); {$IFDEF SUPPORTS_UTF8STRING}overload;{$ENDIF}
// ToString() returns a compact JSON string
function ToString: string; override;
class function JSONToDateTime(const Value: string): TDateTime; static;
class function DateTimeToJSON(const Value: TDateTime; UseUtcTime: Boolean): string; static;
end;
PJsonDataValueArray = ^TJsonDataValueArray;
TJsonDataValueArray = array[0..MaxInt div SizeOf(TJsonDataValue) - 1] of TJsonDataValue;
TJsonArrayEnumerator = class(TObject)
private
FIndex: Integer;
FArray: TJsonArray;
public
constructor Create(AArray: TJSonArray);
function GetCurrent: TJsonDataValueHelper; inline;
function MoveNext: Boolean;
property Current: TJsonDataValueHelper read GetCurrent;
end;
// TJsonArray hold a JSON array and manages the array elements.
TJsonArray = class {$IFDEF USE_FAST_NEWINSTANCE}sealed{$ENDIF}(TJsonBaseObject)
private
FItems: PJsonDataValueArray;
FCapacity: Integer;
FCount: Integer;
function GetString(Index: Integer): string; inline;
function GetInt(Index: Integer): Integer; inline;
function GetLong(Index: Integer): Int64; inline;
function GetULong(Index: Integer): UInt64; inline;
function GetFloat(Index: Integer): Double; inline;
function GetDateTime(Index: Integer): TDateTime; inline;
function GetBool(Index: Integer): Boolean; inline;
function GetArray(Index: Integer): TJsonArray; inline;
function GetObject(Index: Integer): TJsonObject; inline;
function GetVariant(Index: Integer): Variant; inline;
procedure SetString(Index: Integer; const Value: string); inline;
procedure SetInt(Index: Integer; const Value: Integer); inline;
procedure SetLong(Index: Integer; const Value: Int64); inline;
procedure SetULong(Index: Integer; const Value: UInt64); inline;
procedure SetFloat(Index: Integer; const Value: Double); inline;
procedure SetDateTime(Index: Integer; const Value: TDateTime); inline;
procedure SetBool(Index: Integer; const Value: Boolean); inline;
procedure SetArray(Index: Integer; const Value: TJsonArray); inline;
procedure SetObject(Index: Integer; const Value: TJsonObject); inline;
procedure SetVariant(Index: Integer; const Value: Variant); inline;
function GetItem(Index: Integer): PJsonDataValue; inline;
function GetType(Index: Integer): TJsonDataType; inline;
function GetValue(Index: Integer): TJsonDataValueHelper;
procedure SetValue(Index: Integer; const Value: TJsonDataValueHelper);
function AddItem: PJsonDataValue;
function InsertItem(Index: Integer): PJsonDataValue;
procedure Grow;
procedure InternApplyCapacity; inline;
procedure SetCapacity(const Value: Integer);
procedure SetCount(const Value: Integer);
protected
procedure InternToJSON(var Writer: TJsonOutputWriter); override;
class procedure RaiseListError(Index: Integer); static;
public
destructor Destroy; override;
procedure Clear;
procedure Delete(Index: Integer);
// Extract removes the object/array from the array and transfers the ownership to the caller.
function Extract(Index: Integer): TJsonBaseObject;
function ExtractArray(Index: Integer): TJsonArray;
function ExtractObject(Index: Integer): TJsonObject;
procedure Assign(ASource: TJsonArray);
procedure Add(const AValue: string); overload;
procedure Add(const AValue: Integer); overload;
procedure Add(const AValue: Int64); overload;
procedure Add(const AValue: UInt64); overload;
procedure Add(const AValue: Double); overload;
procedure Add(const AValue: TDateTime); overload;
procedure Add(const AValue: Boolean); overload;
procedure Add(const AValue: TJsonArray); overload;
procedure Add(const AValue: TJsonObject); overload;
procedure Add(const AValue: Variant); overload;
function AddArray: TJsonArray;
function AddObject: TJsonObject; overload;
procedure AddObject(const Value: TJsonObject); overload; inline; // makes it easier to add "null"
procedure Insert(Index: Integer; const AValue: string); overload;
procedure Insert(Index: Integer; const AValue: Integer); overload;
procedure Insert(Index: Integer; const AValue: Int64); overload;
procedure Insert(Index: Integer; const AValue: UInt64); overload;
procedure Insert(Index: Integer; const AValue: Double); overload;
procedure Insert(Index: Integer; const AValue: TDateTime); overload;
procedure Insert(Index: Integer; const AValue: Boolean); overload;
procedure Insert(Index: Integer; const AValue: TJsonArray); overload;
procedure Insert(Index: Integer; const AValue: TJsonObject); overload;
procedure Insert(Index: Integer; const AValue: Variant); overload;
function InsertArray(Index: Integer): TJsonArray;
function InsertObject(Index: Integer): TJsonObject; overload;
procedure InsertObject(Index: Integer; const Value: TJsonObject); overload; inline; // makes it easier to insert "null"
function GetEnumerator: TJsonArrayEnumerator;
property Types[Index: Integer]: TJsonDataType read GetType;
property Values[Index: Integer]: TJsonDataValueHelper read GetValue write SetValue; default;
// Short names
property S[Index: Integer]: string read GetString write SetString;
property I[Index: Integer]: Integer read GetInt write SetInt;
property L[Index: Integer]: Int64 read GetLong write SetLong;
property U[Index: Integer]: UInt64 read GetULong write SetULong;
property F[Index: Integer]: Double read GetFloat write SetFloat;
property D[Index: Integer]: TDateTime read GetDateTime write SetDateTime;
property B[Index: Integer]: Boolean read GetBool write SetBool;
property A[Index: Integer]: TJsonArray read GetArray write SetArray;
property O[Index: Integer]: TJsonObject read GetObject write SetObject;
property V[Index: Integer]: Variant read GetVariant write SetVariant;
property Items[Index: Integer]: PJsonDataValue read GetItem;
property Count: Integer read FCount write SetCount;
property Capacity: Integer read FCapacity write SetCapacity;
end;
TJsonNameValuePair = record
Name: string;
Value: TJsonDataValueHelper;
end;
TJsonObjectEnumerator = class(TObject)
protected
FIndex: Integer;
FObject: TJsonObject;
public
constructor Create(AObject: TJsonObject);
function GetCurrent: TJsonNameValuePair; inline;
function MoveNext: Boolean;
property Current: TJsonNameValuePair read GetCurrent;
end;
// TJsonObject hold a JSON object and manages the JSON object properties
TJsonObject = class {$IFDEF USE_FAST_NEWINSTANCE}sealed{$ENDIF}(TJsonBaseObject)
private type
PJsonStringArray = ^TJsonStringArray;
TJsonStringArray = array[0..MaxInt div SizeOf(string) - 1] of string;
private
FItems: PJsonDataValueArray;
FNames: PJsonStringArray;
FCapacity: Integer;
FCount: Integer;
{$IFDEF USE_LAST_NAME_STRING_LITERAL_CACHE}
FLastValueItem: PJsonDataValue;
FLastValueItemNamePtr: Pointer;
procedure UpdateLastValueItem(const Name: string; Item: PJsonDataValue);
{$ENDIF USE_LAST_NAME_STRING_LITERAL_CACHE}
function FindItem(const Name: string; var Item: PJsonDataValue): Boolean;
function RequireItem(const Name: string): PJsonDataValue;
function GetString(const Name: string): string;
function GetBool(const Name: string): Boolean;
function GetInt(const Name: string): Integer;
function GetLong(const Name: string): Int64;
function GetULong(const Name: string): UInt64;
function GetFloat(const Name: string): Double;
function GetDateTime(const Name: string): TDateTime;
function GetObject(const Name: string): TJsonObject;
function GetArray(const Name: string): TJsonArray;
procedure SetString(const Name, Value: string);
procedure SetBool(const Name: string; const Value: Boolean);
procedure SetInt(const Name: string; const Value: Integer);
procedure SetLong(const Name: string; const Value: Int64);
procedure SetULong(const Name: string; const Value: UInt64);
procedure SetFloat(const Name: string; const Value: Double);
procedure SetDateTime(const Name: string; const Value: TDateTime);
procedure SetObject(const Name: string; const Value: TJsonObject);
procedure SetArray(const Name: string; const Value: TJsonArray);
function GetType(const Name: string): TJsonDataType;
function GetName(Index: Integer): string; inline;
function GetItem(Index: Integer): PJsonDataValue; inline;
procedure SetValue(const Name: string; const Value: TJsonDataValueHelper);
function GetValue(const Name: string): TJsonDataValueHelper;
{ Used from the reader, never every use them outside the reader, they may crash your strings }
procedure InternAdd(var AName: string; const AValue: string); overload;
procedure InternAdd(var AName: string; const AValue: Integer); overload;
procedure InternAdd(var AName: string; const AValue: Int64); overload;
procedure InternAdd(var AName: string; const AValue: UInt64); overload;
procedure InternAdd(var AName: string; const AValue: Double); overload;
procedure InternAdd(var AName: string; const AValue: TDateTime); overload;
procedure InternAdd(var AName: string; const AValue: Boolean); overload;
procedure InternAdd(var AName: string; const AValue: TJsonArray); overload;
procedure InternAdd(var AName: string; const AValue: TJsonObject); overload;
function InternAddArray(var AName: string): TJsonArray;
function InternAddObject(var AName: string): TJsonObject;
function InternAddItem(var Name: string): PJsonDataValue;
function AddItem(const Name: string): PJsonDataValue;
procedure Grow;
procedure InternApplyCapacity;
procedure SetCapacity(const Value: Integer);
function GetPath(const NamePath: string): TJsonDataValueHelper;
procedure SetPath(const NamePath: string; const Value: TJsonDataValueHelper);
function IndexOfPChar(S: PChar; Len: Integer): Integer;
procedure PathError(P, EndP: PChar);
procedure PathNullError(P, EndP: PChar);
procedure PathIndexError(P, EndP: PChar; Count: Integer);
protected
procedure InternToJSON(var Writer: TJsonOutputWriter); override;
function FindCaseInsensitiveItem(const ACaseInsensitiveName: string): PJsonDataValue;
public
destructor Destroy; override;
procedure Assign(ASource: TJsonObject);
// ToSimpleObject() maps the JSON object properties to the Delphi object by using the object's
// TypeInfo.
// The object's class must be compiled with the $M+ compiler switch or derive from TPersistent.
procedure ToSimpleObject(AObject: TObject; ACaseSensitive: Boolean = True);
// FromSimpleObject() clears the JSON object and adds the Delphi object's properties.
// The object's class must be compiled with the $M+ compiler switch or derive from TPersistent.
procedure FromSimpleObject(AObject: TObject; ALowerCamelCase: Boolean = False);
procedure Clear;
procedure Remove(const Name: string);
procedure Delete(Index: Integer);
function IndexOf(const Name: string): Integer;
function Contains(const Name: string): Boolean;
// Extract removes the object/array from the object and transfers the ownership to the caller.
function Extract(const Name: string): TJsonBaseObject;
function ExtractArray(const Name: string): TJsonArray;
function ExtractObject(const Name: string): TJsonObject;
function GetEnumerator: TJsonObjectEnumerator;
property Types[const Name: string]: TJsonDataType read GetType;
property Values[const Name: string]: TJsonDataValueHelper read GetValue write SetValue; default;
// Short names
property S[const Name: string]: string read GetString write SetString; // returns '' if property doesn't exist, auto type-cast except for array/object
property I[const Name: string]: Integer read GetInt write SetInt; // returns 0 if property doesn't exist, auto type-cast except for array/object
property L[const Name: string]: Int64 read GetLong write SetLong; // returns 0 if property doesn't exist, auto type-cast except for array/object
property U[const Name: string]: UInt64 read GetULong write SetULong; // returns 0 if property doesn't exist, auto type-cast except for array/object
property F[const Name: string]: Double read GetFloat write SetFloat; // returns 0 if property doesn't exist, auto type-cast except for array/object
property D[const Name: string]: TDateTime read GetDateTime write SetDateTime; // returns 0 if property doesn't exist, auto type-cast except for array/object
property B[const Name: string]: Boolean read GetBool write SetBool; // returns false if property doesn't exist, auto type-cast with "<>'true'" and "<>0" except for array/object
property A[const Name: string]: TJsonArray read GetArray write SetArray; // auto creates array on first access
property O[const Name: string]: TJsonObject read GetObject write SetObject; // auto creates object on first access
property Path[const NamePath: string]: TJsonDataValueHelper read GetPath write SetPath;
// Indexed access to the named properties
property Names[Index: Integer]: string read GetName;
property Items[Index: Integer]: PJsonDataValue read GetItem;
property Count: Integer read FCount;
property Capacity: Integer read FCapacity write SetCapacity;
end;
TJsonSerializationConfig = record
LineBreak: string;
IndentChar: string;
UseUtcTime: Boolean;
NullConvertsToValueTypes: Boolean;
end;
// Rename classes because RTL classes have the same name
TJDOJsonBaseObject = TJsonBaseObject;
TJDOJsonObject = TJsonObject;
TJDOJsonArray = TJsonArray;
var
JsonSerializationConfig: TJsonSerializationConfig = ( // not thread-safe
LineBreak: #10;
IndentChar: #9;
UseUtcTime: True;
NullConvertsToValueTypes: False; // If True and an object is nil/null, a convertion to String, Int, Long, Float, DateTime, Boolean will return ''/0/False
);
implementation
uses
{$IFDEF HAS_UNIT_SCOPE}
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ELSE}
System.DateUtils,
{$ENDIF MSWINDOWS}
System.Variants, System.RTLConsts, System.TypInfo, System.Math, System.SysConst;
{$ELSE}
{$IFDEF MSWINDOWS}
Windows,
{$ELSE}
DateUtils,
{$ENDIF MSWINDOWS}
Variants, RTLConsts, TypInfo, Math, SysConst;
{$ENDIF HAS_UNIT_SCOPE}
{$IF SizeOf(LongWord) <> 4}
// Make LongWord on all platforms a UInt32.
type
LongWord = UInt32;
PLongWord = ^LongWord;
{$IFEND}
resourcestring
RsUnsupportedFileEncoding = 'File encoding is not supported';
RsUnexpectedEndOfFile = 'Unexpected end of file where %s was expected';
RsUnexpectedToken = 'Expected %s but found %s';
RsInvalidStringCharacter = 'Invalid character in string';
RsStringNotClosed = 'String not closed';
RsInvalidHexNumber = 'Invalid hex number "%s"';
RsTypeCastError = 'Cannot cast %s into %s';
RsMissingClassInfo = 'Class "%s" doesn''t have type information. {$M+} was not specified';
RsInvalidJsonPath = 'Invalid JSON path "%s"';
RsJsonPathContainsNullValue = 'JSON path contains null value ("%s")';
RsJsonPathIndexError = 'JSON path index out of bounds (%d) "%s"';
RsVarTypeNotSupported = 'VarType %d is not supported';
{$IFDEF USE_FAST_STRASG_FOR_INTERNAL_STRINGS}
{$IFDEF DEBUG}
//RsInternAsgStringUsageError = 'InternAsgString was called on a string literal';
{$ENDIF DEBUG}
{$ENDIF USE_FAST_STRASG_FOR_INTERNAL_STRINGS}
type
TJsonTokenKind = (
jtkEof, jtkInvalidSymbol,
jtkLBrace, jtkRBrace, jtkLBracket, jtkRBracket, jtkComma, jtkColon,
jtkIdent,
jtkValue, jtkString, jtkInt, jtkLong, jtkULong, jtkFloat, jtkTrue, jtkFalse, jtkNull
);
const
JsonTokenKindToStr: array[TJsonTokenKind] of string = (
'end of file', 'invalid symbol',
'"{"', '"}"', '"["', '"]"', '","', '":"',
'identifier',
'value', 'value', 'value', 'value', 'value', 'value', 'value', 'value', 'value'
);
Power10: array[0..18] of Double = (
1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9,
1E10, 1E11, 1E12, 1E13, 1E14, 1E15, 1E16, 1E17, 1E18
);
// XE7 broke string literal collapsing
var
sTrue: string = 'true';
sFalse: string = 'false';
const
sNull = 'null';
sQuoteChar = '"';
{$IF not declared(varObject)}
varObject = $0049;
{$IFEND}
type
PStrRec = ^TStrRec;
TStrRec = packed record
{$IF defined(CPUX64) or defined(CPU64BITS)} // XE2-XE7 (CPUX64), XE8+ (CPU64BITS)
_Padding: Integer;
{$IFEND}
CodePage: Word;
ElemSize: Word;
RefCnt: Integer;
Length: Integer;
end;
// TEncodingStrictAccess gives us access to the strict protected functions which are much easier
// to use with TJsonStringBuilder than converting FData to a dynamic TCharArray.
TEncodingStrictAccess = class(TEncoding)
public
function GetByteCountEx(Chars: PChar; CharCount: Integer): Integer; inline;
function GetBytesEx(Chars: PChar; CharCount: Integer; Bytes: PByte; ByteCount: Integer): Integer; inline;
function GetCharCountEx(Bytes: PByte; ByteCount: Integer): Integer; inline;
function GetCharsEx(Bytes: PByte; ByteCount: Integer; Chars: PChar; CharCount: Integer): Integer; inline;
end;
{$IFDEF USE_STRINGINTERN_FOR_NAMES}
TStringIntern = record
private type
PJsonStringEntry = ^TJsonStringEntry;
TJsonStringEntry = record
Next: Integer;
Hash: Integer;
Name: string;
end;
PJsonStringEntryArray = ^TJsonStringEntryArray;
TJsonStringEntryArray = array[0..MaxInt div SizeOf(TJsonStringEntry) - 1] of TJsonStringEntry;
PJsonIntegerArray = ^TJsonIntegerArray;
TJsonIntegerArray = array[0..MaxInt div SizeOf(Integer) - 1] of Integer;
private
FStrings: PJsonStringEntryArray;
FBuckets: PJsonIntegerArray;
FCapacity: Integer;
FCount: Integer;
class function GetHash(const Name: string): Integer; static;
procedure Grow;
function Find(Hash: Integer; const S: string): Integer;
procedure InternAdd(AHash: Integer; const S: string);
public
procedure Init;
procedure Done;
procedure Intern(var S: string; var PropName: string);
end;
{$ENDIF USE_STRINGINTERN_FOR_NAMES}
TJsonToken = record
Kind: TJsonTokenKind;
S: string; // jtkIdent/jtkString
case Integer of
0: (I: Integer; HI: Integer);
1: (L: Int64);
2: (U: UInt64);
3: (F: Double);
end;
TJsonReader = class(TObject)
private
{$IFDEF USE_STRINGINTERN_FOR_NAMES}
FIdents: TStringIntern;
{$ENDIF USE_STRINGINTERN_FOR_NAMES}
FPropName: string;
procedure Accept(TokenKind: TJsonTokenKind);
procedure ParseObjectBody(const Data: TJsonObject);
procedure ParseObjectProperty(const Data: TJsonObject);
procedure ParseObjectPropertyValue(const Data: TJsonObject);
procedure ParseArrayBody(const Data: TJsonArray);
procedure ParseArrayPropertyValue(const Data: TJsonArray);
procedure AcceptFailed(TokenKind: TJsonTokenKind);
protected
FLook: TJsonToken;
FLineNum: Integer;
FStart: Pointer;
FLineStart: Pointer;
{$IFDEF SUPPORT_PROGRESS}
FLastProgressValue: NativeInt;
FSize: NativeInt;
FProgress: PJsonReaderProgressRec;
procedure CheckProgress(Position: Pointer);
{$ENDIF SUPPORT_PROGRESS}
function GetLineColumn: NativeInt;
function GetPosition: NativeInt;
function GetCharOffset(StartPos: Pointer): NativeInt; virtual; abstract;
function Next: Boolean; virtual; abstract;
class procedure InvalidStringCharacterError(const Reader: TJsonReader); static;
class procedure StringNotClosedError(const Reader: TJsonReader); static;
class procedure JSONStrToStr(P, EndP: PChar; FirstEscapeIndex: Integer; var S: string;
const Reader: TJsonReader); static;
class procedure JSONUtf8StrToStr(P, EndP: PByte; FirstEscapeIndex: Integer; var S: string;
const Reader: TJsonReader); static;
public
{$IFDEF USE_FAST_NEWINSTANCE}
class function NewInstance: TObject {$IFDEF AUTOREFCOUNT} unsafe {$ENDIF}; override;
procedure FreeInstance; override;
{$ENDIF USE_FAST_NEWINSTANCE}
constructor Create(AStart: Pointer{$IFDEF SUPPORT_PROGRESS}; ASize: NativeInt; AProgress: PJsonReaderProgressRec{$ENDIF});
destructor Destroy; override;
procedure Parse(Data: TJsonBaseObject);
end;
TUtf8JsonReader = class sealed(TJsonReader)
private
FText: PByte;
FTextEnd: PByte;
protected
function GetCharOffset(StartPos: Pointer): NativeInt; override; final;
function Next: Boolean; override; final;
// ARM optimization: Next() already has EndP in a local variable so don't use the slow indirect
// access to FTextEnd.
procedure LexString(P: PByte{$IFDEF CPUARM}; EndP: PByte{$ENDIF});
procedure LexNumber(P: PByte{$IFDEF CPUARM}; EndP: PByte{$ENDIF});
procedure LexIdent(P: PByte{$IFDEF CPUARM}; EndP: PByte{$ENDIF});
public