Fra*_*ank 6 delphi json firemonkey delphi-xe3
我的JSON对象如下所示:
{
"destination_addresses" : [ "Paris, France" ],
"origin_addresses" : [ "Amsterdam, Nederland" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "504 km",
"value" : 504203
},
"duration" : {
"text" : "4 uur 54 min.",
"value" : 17638
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
Run Code Online (Sandbox Code Playgroud)
我需要距离的"504 km"值.我怎样才能做到这一点?
您可以使用DBXJSON自Delphi 2010以来的单位.
试试这个样本
uses
DBXJSON;
{$R *.fmx}
Const
StrJson=
'{ '+
' "destination_addresses" : [ "Paris, France" ], '+
' "origin_addresses" : [ "Amsterdam, Nederland" ], '+
' "rows" : [ '+
' { '+
' "elements" : [ '+
' { '+
' "distance" : { '+
' "text" : "504 km", '+
' "value" : 504203 '+
' }, '+
' "duration" : { '+
' "text" : "4 uur 54 min.", '+
' "value" : 17638 '+
' }, '+
' "status" : "OK" '+
' } '+
' ] '+
' } '+
' ], '+
' "status" : "OK" '+
'}';
procedure TForm6.Button1Click(Sender: TObject);
var
LJsonObj : TJSONObject;
LRows, LElements, LItem : TJSONValue;
begin
LJsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(StrJson),0) as TJSONObject;
try
LRows:=LJsonObj.Get('rows').JsonValue;
LElements:=TJSONObject(TJSONArray(LRows).Get(0)).Get('elements').JsonValue;
LItem :=TJSONObject(TJSONArray(LElements).Get(0)).Get('distance').JsonValue;
ShowMessage(TJSONObject(LItem).Get('text').JsonValue.Value);
finally
LJsonObj.Free;
end;
end;
Run Code Online (Sandbox Code Playgroud)
其中一个可以解析JSON的库是superobject.
要从rows.elements.distanceJSON中获取代码,代码将如下所示:
var
json : ISuperObject;
row_item : ISuperObject;
elements_item: ISuperObject;
begin
json := TSuperObject.ParseFile('C:\json.txt', TRUE); // load whole json here
for row_item in json['rows'] do // iterate through rows array
for elements_item in row_item['elements'] do // iterate through elements array
begin
WriteLn(elements_item['distance'].S['text']); // get distance sub-json and it's text key as string
end;
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18078 次 |
| 最近记录: |