簡體   English   中英

從Json String Delphi XE8獲取特定值

[英]Get specific Value from Json String 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"
  }
}

我想提取銀行的美元的buy_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;

您的代碼中有很多錯誤。 最重要的是您反復使用未經檢查的演員表。 當你寫

TJSONArray(LRows)

您告訴編譯器您知道100%可以確定LRows是從TJSONArray 好吧,不是。 特別是在處理外部數據時,切勿做出此類假設。 然后,您將受到收到數據的異想天開。 請改用選中的演員表

LRows as TJSONArray

現在,這仍然是錯誤的,因為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.

輸出量

45.35
45.80

我建議您花一些時間在JSON站點上,以確保您對術語有非常清楚的了解。 您應該對術語對象,數組和值的含義有清楚的了解。 目前,我認為這是缺乏的。

如果您使用jsonDoc ,它將看起來像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM