-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathuJSON.pas
3020 lines (2714 loc) · 81.4 KB
/
uJSON.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
{
Copyright (C) 2005 Fabio Almeida
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
}
(*
@abstract( Contém todas as classes para manipular o formato JSON. )
As principais classes são : TJSONObject, TJSONArray .
OBS: A unit uJSON foi adaptada de uma implementação para json em Java ver
http://www.json.org .
JSON = JavaScript Object Notation
@author(Jose Fabio Nascimento de Almeida, <[email protected]>)
@created(november 7, 2005)
Utilizando:@br
para criar um objeto json a partir da string:
@code(
s := '{"Commands":[{"Command":"NomeComando", params:{param1:1}}]}' ;@br
json := TJSONObject.create (s);
)
para acessar os elementos:@br
@code(json.getJSONArray ('Commands) // retorna uma TJSONArray dos comandos)
para retornar a string "NomeComando":@br
@code(json.getJSONArray ('Commands).getJSONObject(0).getString('Command'))
*)
unit uJSON;
interface
uses
Windows,SysUtils, Classes, TypInfo;
Type
{ @abstract(Classe pai de todas as classes em uJSON , resolve o problema de
impedância entre a classe java Object e a classe delphi TObject)
}
TZAbstractObject = class
{ retorna true se value é igual ao objeto}
function equals(const Value: TZAbstractObject): Boolean; virtual;
{ código hash do objeto , usa-se o endereço de memória}
function hash: LongInt;
{ clona o objeto
@return ( um TZAbstractObject )}
function Clone: TZAbstractObject; virtual;
{retorna a representação com string do objeto
@return (uma string)}
function toString: string; virtual;
{retorna true se o parâmetro Value é uma instância de TZAbstractObject }
function instanceOf(const Value: TZAbstractObject): Boolean;
end;
{ @abstract(wrapper para ClassCastException do java) }
ClassCastException = class (Exception) end;
{ @abstract(wrapper para NoSuchElementException do java) }
NoSuchElementException = class (Exception) end;
{ @abstract(wrapper para NumberFormatException do java) }
NumberFormatException = class (Exception) end;
{ @abstract(wrapper para NullPointerException do java) }
NullPointerException = class (Exception) end;
{ @abstract(as features não implementadas geram esta exception) }
NotImplmentedFeature = class (Exception) end;
TJSONArray = class ;
_Number = class ;
_String = class;
_Double = class;
NULL = class ;
{ @abstract(exception gerada quando ocorre um erro de parsing) }
ParseException = class (Exception)
constructor create (_message : string ; index : integer);
end;
(**
@abstract(Responsável por auxiliar na análise Léxica de uma string que representa um JSON.)
*)
JSONTokener = class (TZAbstractObject)
public
(**
Construct a JSONTokener from a string.
@param(s A source string.) *)
constructor create (s: string) ;
(**
Back up one character. This provides a sort of lookahead capability,
so that you can test for a digit or letter before attempting to parse
the next number or identifier.
*)
procedure back();
(**
Get the hex value of a character (base16).
@param(c A character between '0' and '9' or between 'A' and 'F' or
between 'a' and 'f'.)
@return(An int between 0 and 15, or -1 if c was not a hex digit.)
*)
class function dehexchar(c : char) :integer;
function more :boolean;
function next() : char; overload ;
function next (c:char ) : char; overload ;
function next (n:integer) : string; overload ;
function nextClean () : char;
function nextString (quote : char) : string;
function nextTo (d : char) : string; overload ;
function nextTo (delimiters : string) : char; overload ;
function nextValue () : TZAbstractObject ;
procedure skipPast (_to : string ) ;
function skipTo (_to : char ): char;
function syntaxError (_message : string) : ParseException;
function toString : string; override;
function unescape (s : string): string;
private
myIndex : integer;
mySource : string;
end;
{ @abstract(Classe que representa um objeto JSON) }
TJSONObject = class (TZAbstractObject)
private
myHashMap : TStringList;
public
(**
Construct an empty TJSONObject.
*)
constructor create; overload;
(**
Construct a TJSONObject from a subset of another TJSONObject.
An array of strings is used to identify the keys that should be copied.
Missing keys are ignored.
@param(jo A TJSONObject.)
@param(sa An array of strings).
*)
constructor create (jo : TJSONObject; sa : array of string); overload;
(**
Construct a TJSONObject from a JSONTokener.
@param(x A JSONTokener object containing the source string.)
@raises(ParseException if there is a syntax error in the source string.)
*)
constructor create (x : JSONTokener); overload;
(**
Construct a TJSONObject from a TStringList.
@param(map A map object that can be used to initialize the contents of
the TJSONObject.)
*)
constructor create (map : TStringList); overload;
(**
Construct a TJSONObject from a string.
This is the most commonly used TJSONObject constructor.
@param(s @html(A string beginning
with <code>{</code> <small>(left brace)</small> and ending
with <code>}</code> <small>(right brace)</small>.))
@raises(ParseException The string must be properly formatted.)
*)
constructor create (s : string); overload;
(**
remove todos os menbros de um objeto JSON .
*)
procedure clean;
(**
sobreescreve o metodo clone de TZAbstractObject
*)
function clone : TZAbstractObject; override;
function accumulate (key : string; value : TZAbstractObject): TJSONObject;
function get (key : string) : TZAbstractObject;
function getBoolean (key : string): boolean;
function getDouble (key : string): double;
function getInt (key : string): integer;
function getJSONArray (key : string) :TJSONArray;
function getJSONObject (key : string) : TJSONObject;
function getString (key : string): string;
function has (key : string) : boolean;
function isNull (key : string) : boolean;
(**
retorna um TStringList com todos os nomes dos atributos do TJSONObject
*)
function keys : TStringList ;
(**
Retorna quantos atributos tem o TJSONObject
*)
function length : integer;
(**
Produce a TJSONArray containing the names of the elements of this
TJSONObject.
@return(A TJSONArray containing the key strings, or null if the TJSONObject
is empty).
*)
function names : TJSONArray;
(**
transforma uma class wrapper _Number (Number em java) em AnsiString
*)
class function numberToString (n: _Number): string;
(**
Make JSON string of an object value.
@html(<p>
Warning: This method assumes that the data structure is acyclical.
)
@param(value The value to be serialized.)
@return( @html(a printable, displayable, transmittable
representation of the object, beginning
with <code>{</code> <small>(left brace)</small> and ending
with <code>}</code> <small>(right brace)</small>.))
*)
class function valueToString(value : TZAbstractObject) : string; overload;
(**
Make a prettyprinted JSON text of an object value.
@html(
<p>
Warning: This method assumes that the data structure is acyclical.
)
@param(value The value to be serialized.)
@param(indentFactor The number of spaces to add to each level of
indentation.)
@param(indent The indentation of the top level.)
@return(@html(a printable, displayable, transmittable
representation of the object, beginning
with <code>{</code> <small>(left brace)</small> and ending
with <code>}</code> <small>(right brace)</small>.))
*)
class function valueToString(value : TZAbstractObject; indentFactor
, indent : integer) : string; overload;
(**
Get an optional value associated with a key.
@param(key A key string.)
@return(An object which is the value, or null if there is no value.)
@raises(NullPointerException caso key = '')
*)
function opt (key : string) : TZAbstractObject;
function optBoolean (key : string): boolean; overload;
function optBoolean (key : string; defaultValue : boolean): boolean; overload;
function optDouble (key : string): double; overload;
function optDouble (key : string; defaultValue : double): double; overload;
function optInt (key : string): integer; overload;
function optInt (key : string; defaultValue : integer): integer; overload;
function optString (key : string): string; overload;
function optString (key : string; defaultValue : string): string; overload;
function optJSONArray (key : string): TJSONArray; overload;
function optJSONObject (key : string): TJSONObject; overload;
function put (key : string; value : boolean): TJSONObject; overload;
function put (key : string; value : double): TJSONObject; overload;
function put (key : string; value : integer): TJSONObject; overload;
function put (key : string; value : string): TJSONObject; overload;
(**
Put a key/value pair in the TJSONObject. If the value is null,
then the key will be removed from the TJSONObject if it is present.
@param(key A key string.)
@param(value An object which is the value. It should be of one of these
types: Boolean, Double, Integer, TJSONArray, TJSONObject, String, or the
TJSONObject.NULL object.)
@return(this.)
@raises(NullPointerException The key must be non-null.)
*)
function put (key : string; value : TZAbstractObject): TJSONObject; overload;
(**
Put a key/value pair in the TJSONObject, but only if the
value is non-null.
@param(key A key string.)
@param(value An object which is the value. It should be of one of these
types: Boolean, Double, Integer, TJSONArray, TJSONObject, String, or the
TJSONObject.NULL object.)
@return(this.)
@raises(NullPointerException The key must be non-null.)
*)
function putOpt (key : string; value : TZAbstractObject): TJSONObject;
class function quote (s : string): string;
function remove (key : string): TZAbstractObject;
procedure assignTo(json: TJSONObject);
function toJSONArray (names : TJSONArray) : TJSONArray;
function toString (): string ; overload; override;
function toString (indentFactor : integer): string; overload;
function toString (indentFactor, indent : integer): string; overload;
destructor destroy;override;
class function NULL : NULL;
end;
{ @abstract(Trata um array JSON = [...])}
TJSONArray = class (TZAbstractObject)
public
destructor destroy ; override;
constructor create ; overload;
constructor create (collection : TList); overload;
constructor create (x : JSONTokener); overload;
constructor create (s : string); overload;
function get (index : integer) : TZAbstractObject;
function getBoolean (index : integer) : boolean;
function getDouble (index : integer) : double;
function getInt (index : integer): integer;
{
Get the TJSONArray associated with an index.
@param(index The index must be between 0 and length() - 1.)
@return(A TJSONArray value.)
@raises(NoSuchElementException if the index is not found or if the
value is not a TJSONArray) }
function getJSONArray (index : integer) : TJSONArray;
function getJSONObject (index : integer) : TJSONObject;
function getString (index : integer) : string;
function isNull (index : integer): boolean;
function join (separator : string) : string;
function length : integer;
function opt (index : integer) : TZAbstractObject;
function optBoolean ( index : integer) : boolean; overload;
function optBoolean ( index : integer; defaultValue : boolean) : boolean; overload;
function optDouble (index : integer) : double; overload;
function optDouble (index : integer; defaultValue :double ) : double ; overload;
function optInt (index : integer) : integer; overload;
function optInt (index : integer; defaultValue : integer) : integer; overload;
function optJSONArray (index : integer) : TJSONArray ; overload;
function optJSONObject (index : integer) : TJSONObject ; overload;
function optString (index : integer) : string; overload;
function optString (index : integer; defaultValue : string) : string; overload;
function put ( value : boolean) : TJSONArray; overload ;
function put ( value : double ) : TJSONArray; overload ;
function put ( value : integer) : TJSONArray; overload ;
function put ( value : TZAbstractObject) : TJSONArray; overload ;
function put ( value: string): TJSONArray; overload;
function put ( index : integer ; value : boolean): TJSONArray; overload ;
function put ( index : integer ; value : double) : TJSONArray; overload ;
function put ( index : integer ; value : integer) : TJSONArray; overload ;
function put ( index : integer ; value : TZAbstractObject) : TJSONArray; overload ;
function put ( index: integer; value: string): TJSONArray; overload;
function toJSONObject (names :TJSONArray ) : TJSONObject ; overload ;
function toString : string; overload; override;
function toString (indentFactor : integer) : string; overload;
function toString (indentFactor, indent : integer) : string; overload;
function toList () : TList;
private
myArrayList : TList;
end;
(** @abstract(wrapper da classe Number do java) *)
_Number = class (TZAbstractObject)
function doubleValue : double; virtual; abstract;
function intValue : integer; virtual; abstract;
end;
(** @abstract(wrapper da classe Boolean do java) *)
_Boolean = class (TZAbstractObject)
class function _TRUE () : _Boolean;
class function _FALSE () : _Boolean;
class function valueOf (b : boolean) : _Boolean;
constructor create (b : boolean);
function toString () : string; override;
function clone :TZAbstractObject; override;
private
fvalue : boolean;
end;
(** @abstract(wrapper da classe Double do java) *)
_Double = class (_Number)
constructor create (s : string); overload;
constructor create (s : _String); overload;
constructor create (d : double); overload;
function doubleValue : double; override;
function intValue : integer; override;
function toString () : string ; override;
class function NaN : double;
function clone :TZAbstractObject; override;
private
fvalue : double;
end;
(** @abstract(wrapper da classe Integer do java) *)
_Integer = class (_Number)
class function parseInt (s : string; i : integer): integer; overload;
class function parseInt (s : _String): integer; overload;
class function toHexString (c : char) : string;
constructor create (i : integer); overload;
constructor create (s : string); overload;
function doubleValue : double; override;
function intValue : integer; override;
function toString () : string; override;
function clone :TZAbstractObject; override;
private
fvalue : integer;
end;
(** @abstract(wrapper da classe String do java) *)
_String = class (TZAbstractObject)
constructor create (s : string);
function equalsIgnoreCase (s: string) : boolean;
function Equals(const Value: TZAbstractObject): Boolean; override;
function toString() : string; override;
function clone :TZAbstractObject; override;
private
fvalue : string;
end;
(** @abstract(utilizado quando se deseja representar um valor NULL ) *)
NULL = class (TZAbstractObject)
function Equals(const Value: TZAbstractObject): Boolean; override;
function toString() : string; override;
end;
var
(** constante para representar um objeto null *)
CNULL : NULL;
implementation
const
CROTINA_NAO_IMPLEMENTADA :string = 'Rotina Não Implementada';
procedure newNotImplmentedFeature () ;
begin
raise NotImplmentedFeature.create (CROTINA_NAO_IMPLEMENTADA);
end;
function getFormatSettings : TFormatSettings ;
var
f : TFormatSettings;
begin
{$IFDEF MSWINDOWS}
SysUtils.GetLocaleFormatSettings (Windows.GetThreadLocale,f);
{$ELSE}
newNotImplmentedFeature();
{$ENDIF}
result := f;
result.DecimalSeparator := '.';
result.ThousandSeparator := ',';
result.CurrencyDecimals := 2;
end;
function HexToInt(S: String): Integer;
var
I, E, F, G: Integer;
function DigitValue(C: Char): Integer;
begin
case C of
'A': Result := 10;
'B': Result := 11;
'C': Result := 12;
'D': Result := 13;
'E': Result := 14;
'F': Result := 15;
else
Result := StrToInt(C);
end;
end;
begin
S := UpperCase(S);
if S[1] = '$' then Delete(S, 1, 1);
if S[2] = 'X' then Delete(S, 1, 2);
E := -1; Result := 0;
for I := Length(S) downto 1 do begin
G := 1; for F := 0 to E do G := G*16;
Result := Result+(DigitValue(S[I])*G);
Inc(E);
end;
end;
{ JSONTokener }
constructor JSONTokener.create(s: string);
begin
self.myIndex := 1;
self.mySource := s;
end;
procedure JSONTokener.back;
begin
if (self.myIndex > 1) then begin
self.myIndex := self.myIndex - 1;
end;
end;
class function JSONTokener.dehexchar(c: char): integer;
begin
if ((c >= '0') and (c <= '9')) then begin
result := (ord(c) - ord('0'));
exit;
end;
if ((c >= 'A') and (c <= 'F')) then begin
result := (ord(c) + 10 - ord('A'));
exit;
end;
if ((c >= 'a') and (c <= 'f')) then begin
result := ord(c) + 10 - ord('a');
exit;
end;
result := -1;
end;
(**
* Determine if the source string still contains characters that next()
* can consume.
* @return true if not yet at the end of the source.
*)
function JSONTokener.more: boolean;
begin
result := self.myIndex <= System.length(self.mySource)+1;
end;
function JSONTokener.next: char;
begin
if (more()) then begin
result := self.mySource[self.myIndex];
self.myIndex := self.myIndex + 1;
exit;
end;
result := chr(0);
end;
(**
* Consume the next character, and check that it matches a specified
* character.
* @param c The character to match.
* @return The character.
* @throws ParseException if the character does not match.
*)
function JSONTokener.next(c: char): char;
begin
result := next();
if (result <> c) then begin
raise syntaxError('Expected ' + c + ' and instead saw ' +
result + '.');
end;
end;
(**
* Get the next n characters.
*
* @param n The number of characters to take.
* @return A string of n characters.
* @raises (ParseException
* Substring bounds error if there are not
* n characters remaining in the source string.)
*)
function JSONTokener.next(n: integer): string;
var
i,j : integer;
begin
i := self.myIndex;
j := i + n;
if (j > System.length(self.mySource)) then begin
raise syntaxError('Substring bounds error');
end;
self.myIndex := self.myIndex + n;
result := copy (self.mySource,i,n); //substring(i, j)
end;
(**
* Get the next char in the string, skipping whitespace
* and comments (slashslash, slashstar, and hash).
* @throws ParseException
* @return A character, or 0 if there are no more characters.
*)
function JSONTokener.nextClean: char;
var
c: char;
begin
while (true) do begin
c := next();
if (c = '/') then begin
case (next()) of
'/': begin
repeat
c := next();
until (not ((c <> #10) and (c <> #13) and (c <> #0)));
end ;
'*': begin
while (true) do begin
c := next();
if (c = #0) then begin
raise syntaxError('Unclosed comment.');
end;
if (c = '*') then begin
if (next() = '/') then begin
break;
end;
back();
end;
end;
end
else begin
back();
result := '/';
exit;
end;
end;
end else if (c = '#') then begin
repeat
c := next();
until (not ((c <> #10) and (c <> #13) and (c <> #0)));
end else if ((c = #0) or (c > ' ')) then begin
result := c;
exit;
end;
end; //while
end;
(**
* Return the characters up to the next close quote character.
* Backslash processing is done. The formal JSON format does not
* allow strings in single quotes, but an implementation is allowed to
* accept them.
* @param quote The quoting character, either
* <code>"</code> <small>(double quote)</small> or
* <code>'</code> <small>(single quote)</small>.
* @return A String.
* @raises (ParseException Unterminated string.)
*)
function JSONTokener.nextString (quote : char): string;
var
c : char;
sb : string;
begin
sb := '';
while (true) do begin
c := next();
case (c) of
#0, #10, #13: begin
raise syntaxError('Unterminated string');
end;
'\': begin
c := next();
case (c) of
'b':
sb := sb + #8;
't':
sb := sb + #9;
'n':
sb := sb + #10;
'f':
sb := sb + #12;
'r':
sb := sb + #13;
'u':
sb := sb+WideChar(StrToInt('$'+next(4)));
{case 'u':
sb.append((char)Integer.parseInt(next(4), 16));
break;
case 'x' : \cx The control character corresponding to x
sb.append((char) Integer.parseInt(next(2), 16));
break;}
else sb := sb + c
end;
end
else begin
if (c = quote) then begin
result := sb;
exit;
end;
sb := sb + c
end;
end;
end;
end;
(**
* Get the text up but not including the specified character or the
* end of line, whichever comes first.
* @param d A delimiter character.
* @return A string.
*)
function JSONTokener.nextTo(d: char): string;
var
sb : string;
c : char;
begin
c := #0;
sb := '';
while (true) do begin
c := next();
if ((c = d) or (c = #0) or (c = #10) or (c = #13)) then begin
if (c <> #0) then begin
back();
end;
result := trim (sb);
exit;
end;
sb := sb + c;
end;
end;
(**
* Get the text up but not including one of the specified delimeter
* characters or the end of line, whichever comes first.
* @param delimiters A set of delimiter characters.
* @return A string, trimmed.
*)
function JSONTokener.nextTo(delimiters: string): char;
var
c : char;
sb : string;
begin
c := #0;
sb := '';
while (true) do begin
c := next();
if ((pos (c,delimiters) > 0) or (c = #0) or
(c = #10) or (c = #13)) then begin
if (c <> #0) then begin
back();
end;
sb := trim(sb);
if (System.length(sb) > 0) then result := sb[1];
exit;
end;
sb := sb + c;
end;
end;
(**
* Get the next value. The value can be a Boolean, Double, Integer,
* TJSONArray, TJSONObject, or String, or the TJSONObject.NULL object.
* @raises (ParseException The source does not conform to JSON syntax.)
*
* @return An object.
*)
function JSONTokener.nextValue: TZAbstractObject;
var
c, b : char;
s , sb: string;
begin
c := nextClean();
case (c) of
'"', #39: begin
result := _String.create (nextString(c));
exit;
end;
'{': begin
back();
result := TJSONObject.create(self);
exit;
end;
'[': begin
back();
result := TJSONArray.create(self);
exit;
end;
end;
(*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*)
sb := '';
b := c;
while ((ord(c) >= ord(' ')) and (pos (c,',:]}/\\\"[{;=#') = 0)) do begin
sb := sb + c;
c := next();
end;
back();
(*
* If it is true, false, or null, return the proper value.
*)
s := trim (sb);
if (s = '') then begin
raise syntaxError('Missing value.');
end;
if (AnsiLowerCase (s) = 'true') then begin
result := _Boolean._TRUE;
exit;
end;
if (AnsiLowerCase (s) = 'false') then begin
result := _Boolean._FALSE;
exit;
end;
if (AnsiLowerCase (s) = 'null') then begin
result := TJSONObject.NULL;
exit;
end;
(*
* If it might be a number, try converting it. We support the 0- and 0x-
* conventions. If a number cannot be produced, then the value will just
* be a string. Note that the 0-, 0x-, plus, and implied string
* conventions are non-standard. A JSON parser is free to accept
* non-JSON forms as long as it accepts all correct JSON forms.
*)
if ( ((b >= '0') and (b <= '9')) or (b = '.')
or (b = '-') or (b = '+')) then begin
if (b = '0') then begin
if ( (System.length(s) > 2) and
((s[2] = 'x') or (s[2] = 'X') ) ) then begin
try
result := _Integer.create(_Integer.parseInt(copy(s,3,System.length(s)),
16));
exit;
Except
on e:Exception do begin
///* Ignore the error */
end;
end;
end else begin
try
result := _Integer.create(_Integer.parseInt(s,
8));
exit;
Except
on e:Exception do begin
///* Ignore the error */
end;
end;
end;
end;
try
result := _Integer.create(s);
exit;
Except
on e:Exception do begin
///* Ignore the error */
end;
end;
try
result := _Double.create(s);
exit;
Except
on e:Exception do begin
///* Ignore the error */
end;
end;
end;
result := _String.create(s);
end;
(**
* Skip characters until the next character is the requested character.
* If the requested character is not found, no characters are skipped.
* @param to A character to skip to.
* @return The requested character, or zero if the requested character
* is not found.
*)
function JSONTokener.skipTo(_to: char): char;
var
c : char;
index : integer;
begin
c := #0;
index := self.myIndex;
repeat
c := next();
if (c = #0) then begin
self.myIndex := index;
result := c;
exit;
end;
until (not (c <> _to));
back();
result := c;
exit;
end;
(**
* Skip characters until past the requested string.
* If it is not found, we are left at the end of the source.
* @param to A string to skip past.
*)
procedure JSONTokener.skipPast(_to: string);
begin
self.myIndex := pos (_to, copy(mySource, self.myIndex, System.length(mySource)));
if (self.myIndex < 0) then begin
self.myIndex := System.length(self.mySource)+1;
end else begin
self.myIndex := self.myIndex + System.length(_to);
end;
end;
(**
* Make a ParseException to signal a syntax error.
*
* @param message The error message.
* @return A ParseException object, suitable for throwing
*)
function JSONTokener.syntaxError(_message: string): ParseException;
begin
result := ParseException.create (_message + toString()+' próximo a : '
+ copy (toString(),self.myIndex,10), self.myIndex);
end;
(**
* Make a printable string of this JSONTokener.
*
* @return " at character [this.myIndex] of [this.mySource]"
*)
function JSONTokener.toString: string;
begin
result := ' at character ' + intToStr(self.myIndex) + ' of ' + self.mySource;
end;
(**
* Convert <code>%</code><i>hh</i> sequences to single characters, and
* convert plus to space.
* @param s A string that may contain
* <code>+</code> <small>(plus)</small> and
* <code>%</code><i>hh</i> sequences.
* @return The unescaped string.
*)
function JSONTokener.unescape(s: string): string;
var
len, i,d,e : integer;
b : string;
c : char;
begin
len := System.length(s);
b := '';
i := 1;
while ( i <= len ) do begin
c := s[i];
if (c = '+') then begin
c := ' ';
end else if ((c = '%') and ((i + 2) <= len)) then begin
d := dehexchar(s[i + 1]);
e := dehexchar(s[i + 2]);
if ((d >= 0) and (e >= 0)) then begin
c := chr(d * 16 + e);
i := i + 2;
end;
end;
b := b + c;
i := i + 1;
end;
result := b ;
end;
{ TJSONObject }
constructor TJSONObject.create;
begin
myHashMap := TStringList.create;
end;
constructor TJSONObject.create(jo: TJSONObject; sa: array of string);
var
i : integer;
begin
create();
for i :=low(sa) to high(sa) do begin
putOpt(sa[i], jo.opt(sa[i]).Clone);
end;
end;
constructor TJSONObject.create(x: JSONTokener);
var