以json格式获取对象?

时间:2016-07-04 05:01:06

标签: json delphi

我在Delphi 2010中编写了以下代码来下载JSON字符串:

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;

当JSON包含单个对象时:

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

代码运作良好。

但是当JSON包含多个对象时:

[{"usertitle":"Yani","userid":"11","username":"887","useremail":"nili_orusoft@yahoo.com","success":"1","error":""},{"usertitle":"Frank","userid":"12","username":"851","useremail":"","success":"1","error":""},{"usertitle":"Mark","userid":"13","username":"950","useremail":"","success":"1","error":""}]

代码在地址00522275"处以"访问冲突而崩溃错误。

1 个答案:

答案 0 :(得分:1)

您的代码存在两个问题:

  1. 您正在泄漏ParseJSONValue()返回的对象。完成使用后,您需要Free()

  2. 您的第二个JSON示例是一个对象数组。 ParseJSONValue()将返回TJSONArray而不是TJSONObject,因此您的as TJSONObject类型转换将失败并引发异常(但不应引发访问冲突)。

  3. 请尝试使用此代码:

    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;