Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Let's try your study TJSONIterator. Delphi
unit uTryStudy_JSONIterator;
interface
uses
System.SysUtils, System.Variants, System.Classes,
System.JSON.Readers, System.JSON.Builders,
System.Generics.Collections, System.Types, System.Rtti;
type
TTryStudy_JSONIterator = class
class function json_to_array<T>(json_str,key_name: String; size_: Integer): TList<TValue>;
end;
implementation
class function TTryStudy_JSONIterator.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;
end.
Owner

mojeld commented Feb 10, 2017

Let's try your study TJSONIterator.
Delphi has many excellent libraries.
So, this is not the only one.
There is also a way to use System.JSON.
This time, I am trying to study TJsonTextReader for the purpose of studying.

How to Use.

program TryStudy_JSONIterator_array;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils, System.Generics.Collections, System.Types, System.Rtti,
  uTryStudy_JSONIterator;

var
  i:      Integer;
  list_:  TList<TValue>;
begin
  try
    list_ := TTryStudy_JSONIterator.json_to_array<String>(
      '{"int_array":[5,10,15],"string_array":["日本語","한글","English"]}',
      'string_array', 3);
    try
      for i := 0 to list_.Count-1 do
        Writeln(list_[i].AsString);
    finally
      list_.DisposeOf;
    end;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment