【问题标题】:Get specific Value from Json String Delphi XE8从 Json String Delphi XE8 获取特定值
【发布时间】:2016-03-02 13:42:12
【问题描述】:

我在 Delphi 中有这个 Json 字符串,

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

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

【问题讨论】:

    标签: json delphi delphi-xe8


    【解决方案1】:

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

    TJSONArray(LRows)
    

    你是在告诉编译器你 100% 知道 LRowsTJSONArray 的后代。好吧,它不是。尤其是当您处理外部数据时,您绝不能做出这样的假设。然后,您将受制于您收到的数据的突发奇想。改用检查演员表

    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 网站,以确保您对术语有非常清楚的了解。您应该清楚地理解术语对象、数组和值的含义。目前我认为这是缺乏的。

    【讨论】:

      【解决方案2】:

      如果你使用jsonDoc,它看起来像这样:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-10
        • 2019-03-30
        • 2013-08-20
        • 2017-11-22
        • 2017-09-19
        相关资源
        最近更新 更多