[英]Can I serialize an interface(_recordset) with TJSONMarshal?
我正在嘗試使用TJSONMarshal(XE4)序列化對象,但是當對象具有_recordset之類的接口屬性時,我遇到了問題
例如
我的課:
TFoo = class
private
FrsFoo: _recordset;
FFooProp: integer;
published
property rsFoo: _recordset read FrsFoo write FrsFoo;
property FooProp: integer read FFooProp write FFooProp;
end;
我的功能:
function TestSerialize: string;
var
JsonMarshal: TJSONMarshal;
Foo: TFoo;
begin
JsonMarshal := TJSONMarshal.Create(TJSONConverter.Create);
Foo := TFoo.Create;
Result := JsonMarshal.Marshal(Foo).ToString;
end;
結果:
{ “類型”: “uTest.TFoo”, “ID”:1, “字段”:{ “FFooProp”:0}}
rsFoo未序列化!
我可以序列化嗎? 還是TJSONMarshal的局限性?
就我而言,我只想序列化_recordsets,所以我的解決方案是:
1)獲取所有_Recordset類型的字段:
function Test.GetRecordsetFieldsFromObject(
AObject: TObject): TStringList;
var
Obj: TRttiType;
Rtti: TRTTIContext;
ObjField: TRttiField;
IntfObj: IInterface;
rsOut: _recordset;
begin
Result := TStringList.Create;
Obj := Rtti.GetType(AObject.ClassType);
for ObjField in Obj.GetFields do
if ObjField.FieldType.TypeKind = tkInterface then
begin
IntfObj := ObjField.GetValue(AObject).AsInterface;
if IntfObj.QueryInterface(_Recordset, rsOut) = 0 then
begin
Result.Add(ObjField.Name);
rsOut := nil;
end;
end;
end;
2)建立的每個字段的寄存器轉換器和轉換器
for FieldName in FieldNameList do
begin
JsonMarshal.RegisterConverter(TFoo, FieldName, function(Data: TObject; Field: String): TListOfStrings
var
Obj: TRttiType;
ObjField: TRttiField;
rsProp: _Recordset;
strStream: TStringStream;
begin
SetLength(Result, 1);
strStream := TStringStream.Create;
try
Obj := Rtti.GetType(data.ClassType);
ObjField := Obj.GetField(Field);
rsProp := ObjField.GetValue(Data).AsInterface as _Recordset;
rsProp.Save(TStreamAdapter.Create(strStream) as IUnknown, adPersistXML);
Result[0] := strStream.DataString;
finally
rsProp := nil;
strStream.Free;
end;
end);
JsonUnMarshal.RegisterReverter(TFoo, FieldName, procedure(Data: TObject; Field: String; Args: TListOfStrings)
var
Obj: TRttiType;
ObjField: TRttiField;
rsProp: _Recordset;
strStream: TStringStream;
begin
rsProp := coRecordset.Create;
strStream := TStringStream.Create(Args[0]);
try
Obj := Rtti.GetType(data.ClassType);
ObjField := Obj.GetField(Field);
strStream.Position := 0;
rsProp.Open(TStreamAdapter.Create(strStream) as IUnknown, EmptyParam, adOpenUnspecified, adLockUnspecified, 0);
ObjField.SetValue(Data, TValue.From<_Recordset>(rsProp));
finally
rsProp := nil;
strStream.Free;
end;
end);
end;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.