Author: Duclos B65275
Below, I wrote a Delphi code.
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 |
//// function TForm1.json_to_array<T>(json_str, key_name: String; size_: Integer): TList<TValue>; var i: Integer; sr_: TStringReader; rd_: TJsonTextReader; jiterator_: TJSONIterator; list_: TList<TValue>; begin sr_ := TStringReader.Create(json_str); rd_ := TJsonTextReader.Create(sr_); jiterator_ := TJSONIterator.Create(rd_); try // Search for key_name if jiterator_.Find(key_name) then begin // Determine whether there is an item. if jiterator_.Recurse then begin list_ := TList<TValue>.Create; for i := 0 to size_-1 do begin jiterator_.Next(); // Get JSON data according to the type. if TypeInfo(T) = TypeInfo(Integer) then list_.Add( jiterator_.AsInteger ) else if TypeInfo(T) = TypeInfo(String) then list_.Add( jiterator_.AsString ); end; end; end; Result := list_; finally jiterator_.DisposeOf; rd_.DisposeOf; sr_.DisposeOf; end; end; |
By writing like this, you can use both String and Integer.
[How to call by using String]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//// procedure TForm1.Button1Click(Sender: TObject); var i: Integer; list_: TList; begin list_ := json_to_array<String>( '{"int_array":[5,10,15,20],"string_array":["日本語","한글","English"]}', 'string_array', 3); try for i := 0 to list_.Count-1 do Memo1.Lines.Append(list_[i].AsString); finally list_.DisposeOf; end; end; |
That was called in the string can be confirmed.
[How to call by using Integer]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
//// procedure TForm1.Button1Click(Sender: TObject); var i: Integer; list_: TList<TValue>; begin list_ := json_to_array<Integer>( '{"int_array":[5,10,15,20],"string_array":["日本語","한글","English"]}', 'int_array', 3); try for i := 0 to list_.Count-1 do Memo1.Lines.Append(IntToStr(list_[i].AsInteger)); finally list_.DisposeOf; end; end; |
[The source is in Gist. ]
https://gist.github.com/mojeld/e5863b845e416d7371ffbaecdd49409f
[Reference material]
http://docwiki.embarcadero.com/CodeExamples/Berlin/en/RTL.JSONIterator
http://docwiki.embarcadero.com/CodeExamples/Berlin/en/RTL.JSONBuilder
Design. Code. Compile. Deploy.
Start Free Trial Upgrade Today
Free Delphi Community Edition Free C++Builder Community Edition