2016-03-02 99 views
0

我有这样的JSON字符串在Delphi中,获取特定值

{ 
    "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" 
    } 
} 

我想提取美元buying_rate和selling_rate为银行BLH

我试试这个,但我得到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; 

回答

6

代码中有很多错误。最重要的是你重复使用未经检查的演员。当你写

TJSONArray(LRows) 

你告诉你知道100%肯定LRowsTJSONArray下降的编译器。呃,事实并非如此。特别是当你处理外部数据时,你不能做出这样的假设。然后,您将受到您收到的数据的兴趣。使用检查转换,而不是

LRows as TJSONArray 

现在,这仍然是错误的,因为LRows不是一个数组。事实上,你的JSON根本没有任何数组。它只是有物体。但是当你使用checked cast时,失败将是一个有意义的错误,而不是访问冲突。

这个程序读取您正在寻找的值:

{$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. 

输出

 
45.35 
45.80 

我劝你在JSON网站花费一些时间,以确保你有一个非常清楚地理解术语。您应该清楚了解术语对象,数组和值的含义。目前我认为缺乏。

0

如果使用jsonDoc它会是这个样子:

StrToFloat(JSON(JSON(JSON(TFile.ReadAllText('C:\desktop\json.txt'))['blh'])['dollar'])['buying_rate'])