HamedAlinejad
HamedAlinejad

Reputation: 161

Get Objects in a json format?

I wrote the below code in Delphi 2010 to download a JSON string:

procedure TForm1.Button1Click(Sender: TObject);
var
  strResult: string;
  listParams: TStringList;
  JO :TJSONObject;
  JV : TJSONValue;
begin
  listParams := TStringList.Create;
  listParams.Add('action=GET');
  listParams.Add('userid=(11,12,13)');
  try
    strResult := idhttp1.Post('http://xxxnet/api/users.php', listParams);
    Memo1.Lines.Text:=strResult;
    JO := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(strResult), 0) as TJSONObject;
    JV := JO.Get(0).JsonValue;
    Memo2.Lines.Add(JV.Value);
  finally
    listParams.Free;
  end;
end;

When the JSON contains a single object:

{"usertitle":"Mark","userid":"13","username":"950","useremail":"","success":"1","error":""}

The code works good.

But when the JSON contains multi objects:

[{"usertitle":"Yani","userid":"11","username":"887","useremail":"[email protected]","success":"1","error":""},{"usertitle":"Frank","userid":"12","username":"851","useremail":"","success":"1","error":""},{"usertitle":"Mark","userid":"13","username":"950","useremail":"","success":"1","error":""}]

The code crashes with an "access violation at address 00522275" error.

Upvotes: 1

Views: 782

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595319

There are two problems with your code:

  1. You are leaking the object that ParseJSONValue() returns. You need to Free() it when you are done using it.

  2. Your second JSON example is an array of objects. ParseJSONValue() will return a TJSONArray instead of a TJSONObject, so your as TJSONObject typecast will fail and raise an exception (but it should not be raising an access violation).

Try this code instead:

procedure TForm1.Button1Click(Sender: TObject);
var
  strResult: string;
  listParams: TStringList;
  JA: TJSONArray;
  JO: TJSONObject;
  JV, JV2: TJSONValue;
begin
  listParams := TStringList.Create;
  try
    listParams.Add('action=GET');
    listParams.Add('userid=(11,12,13)');
    strResult := idhttp1.Post('http://xxxnet/api/users.php', listParams);
  finally
    listParams.Free;
  end;
  Memo1.Lines.Text := strResult;
  JV := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(strResult), 0);
  try
    if JV is TJSONObject then
    begin
      JO := TJSONObject(JV);
      JV2 := JO.Get(0).JsonValue;
      Memo2.Lines.Add(JV2.Value);
    end
    else if JV is TJSONArray then
    begin
      JA := TJSONArray(JV);
      JO := JA.Get(0) as TJSONObject;
      JV2 := JO.Get(0).JsonValue;
      Memo2.Lines.Add(JV2.Value);
    end;
  finally
    JV.Free;
  end;
end;

Upvotes: 1

Related Questions