So I'm trying to write a function in Delphi 10.4 that takes a JSON file out of a SQL table and shows all the items within on a grid.
One of those is in a date format which causes the app to crash, so naturally I try figuring out which it is so I can format it correctly.
However, the method I used to try and find it keep showing the above error:
procedure InjectJSONIntoTable(Query: TFDQuery; MemTable: TFDMemTable; Edit: TEdit);
var
jsonString: string;
jsonArr: TJSONArray;
jsonItem: TJSONObject;
jsonValue: TJSONValue;
i: Integer;
j: Integer;
dummyString: string;
begin
// applies the sql command
Query.SQL.Text := Edit.Text;
Query.Open;
// transforms the sql return back into JSON
jsonString := Query.FieldByName('jdoc').AsString;
jsonArr := TJSonObject.ParseJSONValue(jsonString) as TJSONArray;
// preps the table to receive the data
MemTable.Close;
MemTable.CreateDataSet;
MemTable.Open;
MemTable.Insert;
// appends the data to the table;
for i := 0 to jsonArr.Count -1 do begin
jsonItem := jsonArr.Items[i] as TJSonObject;
for j := 0 to MemTable.Fields.Count - 1 do begin
MemTable.Edit;
jsonValue := jsonItem.GetValue(MemTable.FieldDefs[j].Name);
if jsonValue.ClassType = TDateTime then ShowMessage('tralala');
^ '(' expected but 'THEN' found
MemTable.Fields[j].AsString
:= jsonItem.GetValue(MemTable.FieldDefs[j].Name).Value;
end;
end;
MemTable.Post;
// shows data on the table
end;
And perhaps I'm blind but I honestly can't figure out where the error is coming from.
I've tried a bunch of stuff, switching the order of the elements around, but the error either persists of a bunch of new errors show up.
The TJSONValue.ClassType()
method returns a TClass
, which can only point to TObject
-derived types. TDateTime
is not a class derived from TObject
, so you can't use ClassType = TDateTime
(or ClassType is TDateTime
, like @Dúthomhas suggested).
JSON has no concept of date/time values, so there is no TJSON...
class implemented for TDateTime
. A date/time would just be a string
to JSON.
As @JPRitchey mentioned, you can use the TJSONValue.TryGetValue()
method to convert the value of jsonValue
into a TDateTime
, checking if that conversion succeeds or fails. Just note that TryGetValue<TDateTime>()
will succeed ONLY IF either:
jsonValue
is a TJSONString
object, and the string value is expressed in ISO-8601 format (as the conversion uses DateUtils.ISO8601ToDate()
).
jsonValue
is a TJSONBool
object. The conversion will set the TDateTime
to 1.0
(December 31 1899) or 0.0
(December 30 1899), depending on the boolean value.
Otherwise, TryGetValue<TDateTime>()
will return False
.
If that does not suit your needs, you will have to check the JSON value yourself manually, eg:
var dtValue: TDateTime;
jsonValue := jsonItem.GetValue(MemTable.FieldDefs[j].Name);
// use whatever makes sense for your particular use-case...
if TryStrToDateTime(jsonValue.Value, dtValue) then
ShowMessage('tralala');
MemTable.Fields[j].AsString := jsonValue.Value;