Øystein
Øystein

Reputation: 1223

EConvert exception invalid date time when trying to convert json to object using REST.Json

The following code end up in an exception

'2019.10.5 14:16:14,1000' is not a valid date and time

when trying to parse the json to an object. The problem seems to be the decimal in the date.

  JSonStr := '{"orderNumber": "395409772020_1", "modified": "2019-10-05T14:16:14.9995946Z"}';  
  Order := TJson.JsonToObject<TOrder>(JSonStr);

If I use a date with millisecond precision that rounds downwards i.e "modified": "2019-10-05T14:16:14.4995946Z" it works fine.

I've tried adding options to set the format for the date. Order := TJson.JsonToObject<TOrder>(JSonStr, [joDateFormatParse]);. This prevents the code from crashing, but the DateTime is not recognized and the value ends up with "0".

Anyway around this, or is it simply a bug in the library? I'm running Delphi 10.2 Update 3

Upvotes: 0

Views: 763

Answers (1)

fpiette
fpiette

Reputation: 12292

I built a simple demo program with your code and it works perfectly with Delphi 10.4.1.

Here is the source code for the demo:

unit JsonParseDateDemoMain;

interface

uses
    Winapi.Windows, Winapi.Messages,
    System.SysUtils, System.Variants, System.Classes,
    Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
    REST.Json;

type
    TForm1 = class(TForm)
        Button1: TButton;
        Memo1: TMemo;
        procedure Button1Click(Sender: TObject);
    end;

type
    TOrder = class
    private
        FOrderNumber : String;
        FModified    : TDateTime;
    published
        property OrderNumber : String    read  FOrderNumber write FOrderNumber;
        property Modified    : TDateTime read  FModified    write FModified;
    end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
    JsonStr : String;
    Order   : TOrder;
begin
    JsonStr := '{"orderNumber": "395409772020_1", ' +
                '"modified": "2019-10-05T14:16:14.9995946Z"}';
    Order := TJson.JsonToObject<TOrder>(JsonStr);
    Memo1.Lines.Add(Order.OrderNumber);
    Memo1.Lines.Add(DateTimeToStr(Order.Modified));
    Order.Free;
end;

end.

It is a bug in Delphi version you use.

Upvotes: 1

Related Questions