I am trying to register a custom converter to avoid the inherited properties in TObjectList
- mainly FListHelper
and FOwnsObjects
. But I cannot get the custom converter to register, and the documentation shows no real examples.
(No this is not a duplicate of: How to hide "ownsObjects" and "listHelper" TObjectList's properties from a Json using Delphi (Rest.JSON)?)
I am trying to get a converter Registered - but it seems to never run.
I have wrapped it in a custom class of mine that looks like this:
TMyJsonConverter = class(TJsonConverter)
class function JsonConvert(ObjectToConvert:TObject): string;
private
type
TListOfObjectInterceptor = class(TJSONInterceptor)
function ObjectsConverter(Data: TObject; Field:string): TListOfObjects; override;
end;
end;
function TMyJsonConverter.TListOfObjectInterceptor.ObjectsConverter(Data: TObject; Field:string): TListOfObjects;
begin
raise Exception.Create('converter found');
end;
class function TMyJsonConverter.JsonConvert(ObjectToConvert: TObject): string;
begin
var customConverter := TMyJsonConverter.TListOfObjectInterceptor.Create();
var otherConverter := TMyJsonConverter.Create;
var marshaller := TJSONMarshal.Create(otherconverter);
marshaller.RegisterConverter(
ObjectToConvert.ClassType,
'*',
customConverter.ObjectsConverter
);
var json := marshaller.Marshal(ObjectToConvert);
try
exit(json.ToString);
finally
marshaller.Free;
end;
end;
I have tried to register the types of TObjectConverter
, TObjectsConverter
, TTypeObjectsConverter
but I never seem to get into the conversion function. I can see that the call to register does register the converter, but when I marshal the JSON, it does not find the custom converter again.
Here is a sample structure that highlights the issue, I want to marshal TMySampleDTO
as JSON:
type
TEmployee = class
public
Id: Integer;
Name: string;
end;
TEmployeeList = class(TObjectList<TEmployee>);
TWorktime = class
public
EmployeeId: Integer;
DepartmentId: Integer;
StartTime: TDateTime;
StopTime: TDateTime;
end;
TWorktimeList = class(TObjectList<TWorktime>);
TDepartment = class
public
Id: Integer;
Address: string;
Employees: TEmployeelist;
end;
TDepartmentList = class(TObjectList<TDepartment>);
TMySampleDTO = class
public
Departments: TDepartmentList;
Worktimes: TWorktimeList;
Employees: TEmployeeList;
end;
UPDATE: I got the Converter to run, apparently even though Embarcadero defined the const FIELD_ANY
as '*'
, it doesn't run if you don't specify the exact fieldname, in my case FListHelper
. This raises the next issue though, I also have to give the exact type, as it doesn't check for inheritance. So if my object structure has properties derived from TObjectList<T>
all those lists will be serialized as objects with a list as a property.