I'm attempting to import JSON from a TMemo to a TFDMemTable. Upon execution I get a "Exception EAccessViolation..." error. The line of code that appears to be causing the problem is FDMemTable1.FieldByName('userId').AsString := oProd.GetValue('PutRequest.Item.userId').Value;
which is where I'm appending my first entry to the FDMemTable. I checked the JSON and it appears to be formatted correctly.
Here's my JSON array:
{"Jobs":[{"PutRequest":{"Item":{"userId":{"S":"1"},"WorkOrder":{"S":"29236"},"ServiceDate":{"S":"4/12/2019"}}}},{"PutRequest":{"Item":{"userId":{"S":"1"},"WorkOrder":{"S":"29237"},"ServiceDate":{"S":"4/12/2019"}}}}]}
Here's a snippet from my code:
uses
System.JSON;
procedure TForm1.FormCreate(Sender: TObject);
var
oJson: TJSONObject;
oArr: TJsonArray;
oPair: TJSONPair;
i: Integer;
oProd: TJSONObject;
begin
FDMemTable1.FieldDefs.Add('userId', ftString, 5);
FDMemTable1.FieldDefs.Add('WorkOrder', ftString, 5);
FDMemTable1.FieldDefs.Add('ServiceDate', ftString, 10);
FDMemTable1.Active := True;
oJson := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(Memo1.Lines.Text), 0) as TJSONObject;
try
oArr := oJson.Get('Jobs').JsonValue as TJSONArray;
for i := 0 to oArr.Count - 1 do begin
oProd := oArr.Items[i] as TJSONObject;
FDMemTable1.Append;
FDMemTable1.FieldByName('userId').AsString := oProd.GetValue('PutRequest.Item.userId').Value;
FDMemTable1.FieldByName('WorkOrder').AsString := oProd.GetValue('PutRequest.Item.WorkOrder').Value;
FDMemTable1.FieldByName('ServiceDate').AsString := oProd.GetValue('PutRequest.Item.ServiceDate').Value;
FDMemTable1.Post;
end;
finally
oJson.Free;
end;
end;
I have checked the assignments and values of "oArr" and "oProd" and they appear correct. I'm guessing that I'm not addressing the JSON properly when I'm trying to assign the value to the FDMemTable. How do I resolve this?
You forgot to add
`FDMemTable1.CreateDataSet;`
under
FDMemTable1.FieldDefs.Add('ServiceDate', ftString, 10);
which means your dataSet Fields are not created yet and thus the call to
FDMemTable1.FieldByName('userId').AsString
will return nil and throw an EV when assigning to it
add that line and you are good to go
see this guide by Jim McKeeth (the code under the video) for proper way to use TMemTable
and what it can do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With