【问题标题】:Unable to Parse JSON with Delphi无法使用 Delphi 解析 JSON
【发布时间】:2020-12-07 22:44:06
【问题描述】:

我有一个来自亚马逊的 JSON 字符串。 (https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.json) JSON 的顶部看起来像这样......

我需要检索仅包含 offerCode 和 versionIndexUrl 值的列表。我可以读取一系列报价,但每个报价的密钥不同,所以我不能使用名称(理解、AmazonMWAA 等)。我曾尝试使用元素 [0],但我得到了一个 AV。这是我的相关代码...

procedure Load_AWS_Services;
  var 
  json: string;
  idx: Integer;
  obj: TJSONObject;
  j_array: TJSONArray; // the array of all lineitems/offers
  lineItem : TJSONObject;
  ServiceEntry: TJSONPair;

  begin
  try
    
     JSON :=  DownloadFromURLasString('https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.json');
     obj := TJSONObject.ParseJSONValue(JSON) as TJSONObject;
     
     try
       // Now parse the data...
       j_array := TJSONArray(obj.Get('offers').JsonValue);
       
       // Now loop through each individual item
       for idx := 0 to pred(j_array.size) do
       begin
      
         lineItem := TJSONObject(j_array.Get(idx));
         Main.Memo1.Lines.Add(lineItem.ToString);  // this shows each offer...so good to this point
        ServiceEntry := lineItem.Pairs[0];
        ShowMessage(ServiceEntry.Value);  // AV here

我需要在最后 2 行中更改哪些内容才能在“优惠”内阅读?

【问题讨论】:

  • 'Unable to Parse JSON with Delphi' - 这是完全错误的陈述。您显然能够解析从 AWS 收到的 JSON。
  • @PeterWolf - 如果我无法获得我想要获得的元素,那么我将无法正确解析...
  • 您无法正确访问解析后的 JSON 中的值。答案说明了原因。
  • 请不要张贴图片来代表文本数据。无法复制和粘贴图像以帮助寻找解决方案,它们无法从移动设备读取,并且对屏幕阅读器不友好。将文本作为文本发布并正确格式化以供显示。

标签: json delphi delphi-10.3-rio


【解决方案1】:

offers 字段是 JSON 对象,而不是 JSON 数组(如果您对 TJSONArray 转换使用了 as 运算符,则会引发 EInvalidCast 异常)。

试试这个:

procedure Load_AWS_Services;
var 
  json: string;
  idx: Integer;
  j_val: TJSONValue;
  j_obj: TJSONObject;
  j_pair: TJSONPair;
  offers: TJSONObject;
  lineItem : TJSONObject;
begin
  try
    json := DownloadFromURLasString('https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/index.json');
    j_val := TJSONObject.ParseJSONValue(json);
    try
      j_obj := j_val as TJSONObject;

      // Now parse the data...
      offers := j_obj.GetValue('offers') as TJSONObject;
       
      // Now loop through each individual item
      for idx := 0 to pred(offers.Count) do
      begin
        j_pair := offers.Get(idx);
        Main.Memo1.Lines.Add(j_pair.JsonString.Value);
        lineItem := j_pair.JsonValue as TJSONObject;
        ShowMessage(lineItem.GetValue('offerCode').Value);
        ShowMessage(lineItem.GetValue('versionIndexUrl').Value);
        ...
      end;
    finally
      j_val.Free;
    end;
  except
    ...
  end;
end;

【讨论】:

  • 太棒了...效果很好..谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-02
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多