SuperObject - 全部提取

时间:2012-12-29 15:01:54

标签: json delphi delphi-xe2 superobject

如何从通用JSON 获取所有'id'成员值不知道它的结构。因为它非常复杂而且它有很多子对象。它必须循环遍历所有子对象。

对于那些继续询问JSON示例的人来说再次。我的问题是如何在我的案例“id”中从任何具有此成员的通用JSON中提取成员值

1 个答案:

答案 0 :(得分:10)

如果你不知道从某个地方收到的JSON的结构,重要的是要注意JSON“简单地”是一个复合模式,你可以像任何其他复合结构一样遍历它。以下示例遍历JSON文本中的完整结构,并打印名为“id”的任何成员的路径。

procedure ParseJSON;
var
  JSONText: string;
  JSON: ISuperObject;
begin
  // Retrieve JSON as a string into JSONText variable any way you like.
  JSON := SO(JSONText);
  ProcessObject(JSON.AsObject);
end;

procedure ProcessObject(const aAsObject: TSuperTableString; const aPrefix: string = '');
var
  Names: ISuperObject;
  Name: string;
  Items: ISuperObject;
  Item: ISuperObject;
  idx: Integer;
  Value: string;
  ArrayItem: ISuperObject;
begin
  if Assigned(aAsObject) then
  begin
    Names := aAsObject.GetNames;
    Items := aAsObject.GetValues;

    for idx := 0 to Items.AsArray.Length - 1 do
    begin
      Name := Names.AsArray[idx].AsString;
      Item := Items.AsArray[idx];
      if Item.DataType = stObject then
        Value := '<Object>'
      else if Item.DataType = stArray then
        Value := '<Array>'
      else
        Value := Item.AsString;

      if SameText(Name, 'id') then
        WriteLn(Format('%s: %s', [aPrefix + Name, Value]));

      if Item.DataType = stArray then
        for ArrayItem in Item do
          ProcessObject(ArrayItem.AsObject, aPrefix + Name + '.');

      if Item.DataType = stObject then
        ProcessObject(Item.AsObject, aPrefix + Name + '.');
    end;
  end;
end;