I have the following Json Array from url link.
[{"DATE":"01/10/2021","QUANTITY":4,"UNITPRICE":23.9},
{"DATE":"01/10/2021","QUANTITY":5.85,"UNITPRICE":23.9},
{"DATE":"30/09/2021","QUANTITY":10,"UNITPRICE":23.9},
{"DATE":"04/08/2021","QUANTITY":10,"UNITPRICE":28.83},
{"DATE":"01/07/2021","QUANTITY":1,"UNITPRICE":2.06},
{"DATE":"01/07/2021","QUANTITY":1,"UNITPRICE":2.06},
{"DATE":"30/06/2021","QUANTITY":1,"UNITPRICE":2.06},
{"DATE":"30/06/2021","QUANTITY":1,"UNITPRICE":2.06}]
I want to extract a particular data from the above kind of JSON structure and later to Show in Memo or ListView the values of DATE or one of the other elements.The proper thing to do is to create an Array of Json and put the data in? When i run my code and click the button it doesnt show anything. Also Im new to Delphi. Here is the code i have wrote:
function GetURLAsString(const aurl: string): string;
var
IdHTTP1 : TidHTTP;
begin
IdHTTP1 := TIdHTTP.Create(nil);
try
IdHTTP1.IOHandler := TidSSLIOHandlerSocketOpenSSL.Create(IdHTTP1);
result := IdHTTP1.Get(aurl);
finally
IdHTTP1.Free;
end;
end;
procedure TForm4.Button1Click(Sender: TObject);
var
jso : TJsonObject;
js : TJsonObject;
jsv : TJsonValue;
jsa : TJsonArray;
jsp : TJsonPair;
data : string;
i : integer;
LItem : TListViewItem;
begin
try
data := GetURLAsString('http://....');
except
on E: exception do
end;
try
jsv := TJSONObject.ParseJSONValue(data);
try
jso := jsv as TJSONObject;
jsa:=TJSONArray.Create();
jsp := TJSONPair.Create('Array', jsa);
js.AddPair(jsp);
jsp := jso.Get('Array');
jsa := jsp.JsonValue as TJsonArray;
for I := 0 to jsa.Size - 1 do
begin
jso := jsa.Get(i) as TJsonObject;
for jsp in jso do
begin
if jsp.JsonString.Value = 'DATE' then
begin
form4.ListView1.BeginUpdate;
LItem := form4.ListView1.Items.Add;
LItem.Text := jso.GetValue('DATE').ToString;
form4.ListView1.EndUpdate;
end;
end;
end;
finally
jsv.Free;
end;
except
on E: exception do
end;
end;
CodePudding user response:
I suspect you will get an access violation because you access the method AddPair of the js variable which has not been initialized, and since you catch the exception and igores it, you do not see it.
You are however overcomplicating the solution, which results in bugs. This should work:
jsa := jsv as TJSONArray;
form4.ListView1.BeginUpdate;
try
for I := 0 to jsa.Size - 1 do
begin
jso := jsa.Get(i) as TJsonObject;
LItem := form4.ListView1.Items.Add;
LItem.Text := jso.GetValue('DATE').ToString;
end;
finally
form4.ListView1.EndUpdate;
end;
finally
jsv.Free;
end;