使用SuperObject从JSON请求中读取特定值

时间:2014-11-23 22:41:21

标签: json delphi superobject

您好我在JSON格式的Web API中获得了下一个结果:

[
   {
      "$id":"47",
      "CodISO":"BIH",
      "ES":"Bosnia y Herzegovina",
      "EN":"Bosnia and Herzegovina"
   },
   {
      "$id":"48",
      "CodISO":"BLR",
      "ES":"Bielorrusia",
      "EN":"Belarus"
   },
   {
      "$id":"49",
      "CodISO":"BLZ",
      "ES":"Belice",
      "EN":"Belize"
   },
   {
      "$id":"50",
      "CodISO":"BOL",
      "ES":"Bolivia",
      "EN":"Bolivia"
   },
   {
      "$id":"51",
      "CodISO":"BON",
      "ES":"Bonaire",
      "EN":"Bonaire"
   },
   {
      "$id":"52",
      "CodISO":"BOT",
      "ES":"Botsuana",
      "EN":"Botswana"
   },
   {
      "$id":"53",
      "CodISO":"BRA",
      "ES":"Brasil",
      "EN":"Brazil"
   },
   {
      "$id":"54",
      "CodISO":"BRB",
      "ES":"Barbados",
      "EN":"Barbados"
   }
]

现在,我想要阅读项目' ES'其中item' CodISO'的价值=' BOL'在Delphi SuperObject中,我无法找到解决方案,花了一整天的时间来尝试它。

我不知道如何使用Embarcadero TJSONValueTJSONObjectTJSONArray迭代SuperObject元素。我是SuperObject的新手:

var
  json: ISuperObject;
  Retriever: TIdHTTP;
  Url: string;
  AnsiStr: AnsiString;
begin
  URL := Form1.RestClient1.BaseURL;
  try
    Retriever := TIdHTTP.Create(nil);
    try
      AnsiStr := Retriever.Get(Url);
      json := SO(AnsiStr); 
      { Here code to iterate with json elements in SuperObject.......
      .
      .
      .
      .
      }             
    finally
      Retriever.Free;
    end;
  except
    on E: Exception do
      ShowMessage(E.ClassName + ': ' + E.Message);
  end;
End;

1 个答案:

答案 0 :(得分:1)

正如Rufo爵士所说,你需要阅读SuperObject documentation

尝试这样的事情:

var
  JsonArr, JsonObj: ISuperObject;
  Retriever: TIdHTTP;
  Url, JsonStr, ES: string;
  I: Integer;
begin
  URL := Form1.RestClient1.BaseURL;
  try
    Retriever := TIdHTTP.Create(nil);
    try
      JsonStr := Retriever.Get(Url);
    finally
      Retriever.Free;
    end;
    JsonArr := SO(JsonStr).AsArray; 
    for I := 0 to JsonArr.Length-1 do
    begin
      JsonObj := JsonArr.O[I];
      if JsonObj.S['CodISO'] = 'BOL' then
      begin
        ES := JsonObj.S['ES'];
        Break;
      end;
    end;
  except
    on E: Exception do
      ShowMessage(E.ClassName + ': ' + E.Message);
  end;
end;