在Delphi XE7中从URL检索JSON数据

时间:2017-12-25 15:39:13

标签: json delphi delphi-xe7

我正在尝试从URL获取JSON数据。我正在尝试连接的网站是:

http://www.bitven.com/assets/js/rates.js

它包含以下JSON字符串:

<?php
namespace Drupal\telegram\Controller;

use Drupal\Core\Controller\ControllerBase;

class TelegramController extends ControllerBase {

public function telegram() {

$update = file_get_contents("php://input");
$update = json_decode($update, TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];

if (isset($chatId) and isset($message)) {
    sendMessage($chatId, $message);
    $url = "https://api.telegram.org/bot504387877:AAFHnQe-AdscpSZN42yY-JYem5jwdJc131Q/sendMessage?chat_id=" . $chatId . "&text=" . $message;
}
file_get_contents($url);

$build['#theme'] = 'new';
return $build;

}

}

我需要获取USD_TO_BSF_RATE的值,该值在我提到的网站中每5分钟更新一次。我的代码如下:

{
  "USD_TO_BSF_RATE": 112268.29,
  "BTC_TO_USD_RATE": 13870.9,
  "ETH_TO_USD_RATE": 752.222,
  "BCH_TO_USD_RATE": 2960.81,
  "LTC_TO_USD_RATE": 272.476,
  "XRP_TO_USD_RATE": 1.01954,
  "ETC_TO_USD_RATE": 31.1101,
  "DASH_TO_USD_RATE": 1178.0,
  "ZEC_TO_USD_RATE": 561.377,
  "XMR_TO_USD_RATE": 354.709
}

我的应用无法正常运行,也无法返回任何消息。它只会崩溃。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您的GetUrlContent()功能编码不正确。它需要看起来像这样:

function GetUrlContent(s: string): string;
var
  IdHTTP1: TIdHTTP;
begin
  IdHTTP1 := TIdHTTP.Create;
  try
    Result := IdHTTP1.Get(s);
  finally
    IdHTTP1.Free;
  end;
end;

您的DolarUpdate()程序看起来应该更像这样:

procedure DolarUpdate;
var
  json: string;
  obj: TJSONObject;
  url: string;
begin
  try
    json := GetUrlContent('http://www.bitven.com/assets/js/rates.js');
    obj := TJSONObject.ParseJSONValue(json) as TJSONObject;
    if obj = nil then raise Exception.Create('Error parsing JSON');
    try
      TabbedForm.Edit2.Text := obj.Values['USD_TO_BSF_RATE'].Value;
    finally
      obj.Free;
    end;
  except
    on E : Exception do
    begin
      ShowMessage('Error' + sLineBreak + E.ClassName + sLineBreak + E.Message);
    end;
  end;
end;