Dis*_*son 2 delphi json delphi-xe8
我在Delphi中有这个Json String,
{
"bpd": {
"euro": {
"buying_rate": "48.50",
"selling_rate": "52.70"
},
"dollar": {
"buying_rate": "45.30",
"selling_rate": "45.80"
},
"source": "https://www.popularenlinea.com/_api/web/lists/getbytitle('Rates')/items"
},
"blh": {
"euro": {
"buying_rate": "48.50",
"selling_rate": "52.00"
},
"dollar": {
"buying_rate": "45.35",
"selling_rate": "45.80"
},
"source": "http://www.blh.com.do/Inicio.aspx"
}
}
Run Code Online (Sandbox Code Playgroud)
我想为银行blh提取buy_rate和sell_rate美元
我试试这个,但我得到AV
var
LJsonObj : TJSONObject;
LRows, LElements, LItem : TJSONValue;
begin
LJsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(s),0) as TJSONObject;
try
LRows:=LJsonObj.Get(0).JsonValue;
LElements:=TJSONObject(TJSONArray(LRows).Get(0)).Get(0).JsonValue;
LItem :=TJSONObject(TJSONArray(LElements).Get(0)).Get(0).JsonValue;
ShowMessage(TJSONObject(LItem).Get('buying_rate').JsonValue.Value);
finally
LJsonObj.Free;
end;
Run Code Online (Sandbox Code Playgroud)
Dav*_*nan 10
您的代码中存在许多错误.最重要的是你反复使用未经检查的演员阵容.当你写作
TJSONArray(LRows)
Run Code Online (Sandbox Code Playgroud)
你告诉编译器你知道100%肯定LRows是后来的TJSONArray.嗯,事实并非如此.特别是当您处理外部数据时,您不能做出这样的假设.然后,您将受到所收到数据的突发奇想.请使用选中的强制转换
LRows as TJSONArray
Run Code Online (Sandbox Code Playgroud)
现在,这仍然是错误的,因为LRows它不是一个数组.实际上你的JSON根本没有任何数组.它只有对象.但是当您使用经过检查的强制转换时,失败将是一个有意义的错误,而不是访问冲突.
该程序读取您要查找的值:
{$APPTYPE CONSOLE}
uses
System.SysUtils, System.JSON, System.IOUtils;
procedure Main;
var
s: string;
LJsonObj: TJSONObject;
blh: TJSONObject;
dollar: TJSONObject;
rate: TJSONString;
begin
s := TFile.ReadAllText('C:\desktop\json.txt');
LJsonObj := TJSONObject.ParseJSONValue(TEncoding.UTF8.GetBytes(s), 0) as TJSONObject;
try
blh := LJsonObj.GetValue('blh') as TJSONObject;
dollar := blh.GetValue('dollar') as TJSONObject;
rate := dollar.GetValue('buying_rate') as TJSONString;
Writeln(rate.Value);
rate := dollar.GetValue('selling_rate') as TJSONString;
Writeln(rate.Value);
finally
LJsonObj.Free;
end;
end;
begin
try
Main;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Run Code Online (Sandbox Code Playgroud)
产量
45.35 45.80
我建议您花一些时间在JSON网站上,以确保您对术语有一个非常清楚的了解.您应该清楚地理解术语对象,数组和值的含义.目前我认为这是缺乏的.
| 归档时间: |
|
| 查看次数: |
5604 次 |
| 最近记录: |