2014-11-23 78 views
-1

你好,我得到一个JSON格式的网络API下一结果JSON请求的特定值:阅读使用超对象

[ 
    { 
     "$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”,其中的价值在Delphi SuperObject中,项目'CodISO'='BOL',我无法找到解决方案,花了一整天的时间尝试它。

我不知道如何使用SuperObject元素迭代,因为我使用Embarcadero TJSONValueTJSONObjectTJSONArray。我是一个新手与超对象:

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; 
+2

“我无法找到解决办法,采取了一整天它” - 你究竟什么尝试?请显示你的代码。如果你真的看SuperObject的可用API,这应该不会超过几分钟。 JSON没有任何类似于XML的XPath,因此您必须手动迭代这些项目。从根数组开始,根据需要循环访问数组的项目,每次读取它们的“CodISO”和“ES”字段,然后在找到匹配项时断开循环。就那么简单。 – 2014-11-23 23:38:17

+2

你看看超级对象的[readme.html](https://superobject.googlecode.com/git/readme.html)吗?这是自述文件的意图,您应该阅读以获取更多信息 – 2014-11-24 00:28:47

回答

1

正如入佛门爵士说,你需要阅读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;