RTL.JSONReader
Contents
Description
This code snippet shows how to create and use a JSON Reader using System.JSON.Readers.
Code
The following JSON object contains information about purchase records from a website.
{"Transaction":[
{"id":662713, "firstName":"John", "lastName":"Doe", "price": 2.1, "parent_id": null, validated:true},
{"id":662714, "firstName":"Anna", "lastName":"Smith", "price": 4.5, "parent_id": null, validated: false},
{"id":662715, "firstName":"Peter", "lastName":"Jones", "price": 3.6, "parent_id": null, validated: true}
]}
The sample consists of a TMemo that shows the result of parsing a JSON object. The sample analyses the JSON tokens and adds a line to the TMemo when opening and closing objects/arrays.
The Path property shows the path to each property of the elements in the array.
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
Sr: TStringReader;
Reader: TJsonTextReader;
procedure CreateReader(Str: string);
public
{ Public declarations }
procedure ParseObject;
end;
uses System.JSON.Readers, System.JSON.Types;
procedure TForm1.Button1Click(Sender: TObject);
begin
ParseObject;
end;
procedure TForm1.CreateReader(Str: string);
begin
if Reader <> nil then
Reader.Free;
if Sr <> nil then
Sr.Free;
Sr := TStringReader.Create(Str);
Reader := TJsonTextReader.Create(Sr);
end;
procedure TForm1.ParseObject;
begin
CreateReader(
'{"Transaction":[' + sLineBreak
+ '{"id":662713, "firstName":"John", "lastName":"Doe", "price": 2.1, "parent_id": null, validated: true},' + sLineBreak
+ '{"id":662714, "firstName":"Anna", "lastName":"Smith", "price": 4.5, "parent_id": null, validated: false},' + sLineBreak
+ '{"id":662715, "firstName":"Peter", "lastName":"Jones", "price": 3.6, "parent_id": null, validated: true}' + sLineBreak
+ ']}'
);
while Reader.read do
case Reader.TokenType of
TJsonToken.startobject:
Memo1.Lines.Add('(StartObject) ' + '- Token Path : ' + Reader.Path);
TJsonToken.StartArray:
Memo1.Lines.Add('(StartArray) ' + '- Token Path : ' + Reader.Path );
TJsonToken.PropertyName:
Memo1.Lines.Add('PropertyName : ' + Reader.Value.ToString + '- Token Path : ' + Reader.Path );
TJsonToken.String:
Memo1.Lines.Add('String Value : ' + Reader.Value.ToString + '- Token Path : ' + Reader.Path);
TJsonToken.Integer:
Memo1.Lines.Add('Integer Value : ' + Reader.Value.ToString + '- Token Path : ' + Reader.Path);
TJsonToken.Float:
Memo1.Lines.Add('Float Value : ' + Reader.Value.ToString + '- Token Path : ' + Reader.Path);
TJsonToken.Boolean:
Memo1.Lines.Add('Boolean Value : ' + Reader.Value.ToString + '- Token Path : ' + Reader.Path);
TJsonToken.Null:
Memo1.Lines.Add('Null Value : ' + Reader.Value.ToString + '- Token Path : ' + Reader.Path);
TJsonToken.EndArray:
Memo1.Lines.Add('(EndArray) ' + '- Token Path : ' + Reader.Path);
TJsonToken.EndObject:
Memo1.Lines.Add('(EndObject) ' + '- Token Path : ' + Reader.Path);
end;
end;