Read a specific value from a JSON request using SuperObject

1.3k views Asked by At

Hello I get the next result in a web API in JSON format:

[
   {
      "$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"
   }
]

Now, I want read the value from item 'ES' where the value of item 'CodISO' = 'BOL' in Delphi SuperObject, I'm not able to find the solution, took all day trying it.

I don't know how iterate with SuperObject elements as I do it with Embarcadero TJSONValue, TJSONObject, TJSONArray. I'm a newbie with 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

There are 1 answers

0
Remy Lebeau On BEST ANSWER

As Sir Rufo said, you need to read the SuperObject documentation.

Try something like this:

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;