我有以下问题:
使用 Delphi XE - 考虑一下:
type
TMyClass = Class
public
FaString : String;
FaStringList : TStringList;
FMar : TJsonMarshal;
procedure RegisterConverters;
function Marshal : TJsonObject; // should handle marshalling
end;
RegisterConverters 看起来像这样。
procedure TMyClass.RegisterConverters;
begin
// try and catch the marshaller itself.
FMar.RegisterConverter(TJsonMarshal, 'FMar',
function(Data : TObject; Field:String): TObject
begin
Exit(nil); // Since we cannot marshal it - and we dont need it anyways.
end);
// catch TStringList
FMar.RegisterConverter(TStringList, 'FaStringList',
function(Data: TObject; Field:String): TListOfStrings
var
i, count: integer;
begin
count := TStringList(Data).count;
SetLength(Result, count);
for i := 0 to count - 1 do
Result[i] := TStringList(Data)[i];
end);
end;
和编码(marshal)方法:
function TMyClass.Marshal: TJSONObject;
begin
if FMar = nil then
FMar := TJSONMarshal.Create(TJSONConverter.Create);
try
RegisterConverters;
try
Result := FMar.Marshal(Self) as TJSONObject;
except
Result := nil;
end;
finally
FMar.Free;
end;
end;
然后我们可以这样做:
var
aObj : TMyClass;
ResultString : String;
begin
aObj := TMyClass.Create;
aObj.FaString := 'Test string';
aObj.FaStringList := TStringList.Create;
aObj.FaStringList.Add('stringliststring #1');
aObj.FaStringList.Add('stringliststring #2');
aObj.FaStringList.Add('stringliststring #3');
aObj.FaStringList.Add('stringliststring #4');
// StringList and JsonMarshal should be handled by converter
ResultString := (aObj.Marshal).ToString;
end;
但我根本无法让它工作。场转换器不会被触发?
我在这里做错了吗?或者我应该看看我的 Delphi XE 安装(也许它是被骗的)?
最佳答案
从“内部”执行编码(marshal)时,您必须正确设置它:-)
procedure TMyClass.RegisterConverters;
begin
// try and catch the marshaller itself.
FMar.RegisterConverter(ClassType, 'FMar',
function(Data : TObject; Field:String): TObject
begin
Exit(nil); // Since we cannot marshal it - and we dont need it anyways.
end);
// catch TStringList
FMar.RegisterConverter(ClassType, 'FaStringList',
function(Data: TObject; Field:String): TListOfStrings
var
i, count: integer;
begin
count := TStringList(Data).count;
SetLength(Result, count);
for i := 0 to count - 1 do
Result[i] := TStringList(Data)[i];
end);
end;
不同之处在于使用 ClassType 作为对 RegisterConverter 的调用中的类型。
否则无法到达指定的字段 - 我应该看到的!
关于delphi - 具有内置编码的类。为什么现场转换器不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7608415/