2016-03-02 101 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'])