Search code examples
jsondelphidelphi-xe7

Retrieving JSON data from URL in Delphi XE7


I'm trying to get JSON data from an URL. The site I'm trying to connect is:

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

It contains the following JSON string:

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

I need to get the value of USD_TO_BSF_RATE, which is updated every 5 minutes in the site I mentioned. My code looks like:

uses
  ... System.JSON, IdHTTP;

function  GetUrlContent(s: string): string;
var
  IdHTTP1: TIdHTTP;
begin
  IdHTTP1.Create;
  GetUrlContent:=IdHTTP1.Get(s);
  IdHTTP1.Destroy;
end;

procedure DolarUpdate;
var
  json: string;
  obj: TJSONObject;
  url: string;
begin
  try
    json:=GetUrlContent('http://www.bitven.com/assets/js/rates.js');
    try
      obj := TJSONObject.ParseJSONValue(json) as TJSONObject;
      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;

My app doesn't function correctly, nor return any messages. It only crashes.

What am I doing wrong?


Solution

  • Your GetUrlContent() function is not coded correctly. It needs to look like this instead:

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

    And your DolarUpdate() procedure should look more like this instead:

    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;