尝试在运行时将对象转换为JSON,我的RTTI错误不足。 对象是:
{$M+}
{$TYPEINFO ON}
{$METHODINFO ON}
{$RTTI EXPLICIT METHODS([vcPublic, vcPublished]) PROPERTIES([vcPublic, vcPublished])}
TMyPacket = class(TObject)
Private
FID: TGUID;
FToIP: string;
FToPort: integer;
FSent: boolean;
FSentAt: TDateTime;
FAck: boolean;
FTimeOut: Cardinal;
FDataToSendSize: UINT64;
FDataToSend: AnsiString;
public
constructor create;
destructor free;
published
property ID: TGUID read FID write FID;
property ToIP: string read FToIP write FToIP;
property ToPort: integer read FToPort write FToPort;
property Sent: boolean read FSent write FSent;
property SentAt: TDateTime read FSentAt write FSentAt;
property Ack: boolean read FAck write FAck;
property TimeOut: Cardinal read FTimeOut write FTimeOut;
property DataToSend: AnsiString read FDataToSend write FDataToSend;
end;
稍后在代码中:
var fpacket: TMYPacket;
begin
fpacket := TVWTCPPacket.create;
//assign value to class properties
memo1.Lines.Text := TJson.ObjectToJsonString(fpacket); //throws error
并获取JSON转换错误。 有没有人知道Delphi Berlin 10.1出了什么问题? 我确实记得XE2上的一些RTTI问题,但不确定上面发生的事情是否与Delphi旧bug有关。
答案 0 :(得分:6)
进入System.Rtti
并在第TRttiField.GetValue
行的if ft = nil then
放置一个断点并设置断点条件ft = nil
(如果你将断点放在下一行中)由于优化,我无法看到该字段的名称。
当您的调试器停在那里时,您可以检查Self.Name
(Ctrl + F7),它会告诉您D4
这是您的TGuid的第四个字段。这是因为JsonReflect通过序列化字段来递归地序列化记录。由于D4
被声明为array[0..7] of Byte
,因此它不包含类型信息(see also)。
要解决此问题,请为TGUID
:
type
TGuidInterceptor = class(TJSONInterceptor)
public
function StringConverter(Data: TObject; Field: string): string; override;
procedure StringReverter(Data: TObject; Field: string; Arg: string); override;
end;
function TGuidInterceptor.StringConverter(Data: TObject;
Field: string): string;
var
ctx: TRttiContext;
begin
Result := ctx.GetType(Data.ClassInfo).GetField(Field).GetValue(Data).AsType<TGuid>.ToString;
end;
procedure TGuidInterceptor.StringReverter(Data: TObject; Field, Arg: string);
var
ctx: TRttiContext;
begin
ctx.GetType(Data.ClassInfo).GetField(Field).SetValue(Data, TValue.From(TGuid.Create(Arg)));
end;
并相应地标记字段:
[JsonReflect(ctString, rtString, TGuidInterceptor)]
FID: TGUID;
答案 1 :(得分:0)
TGUID
种字段没有生成RTTI。
因此,为了序列化您的类,您可以使用getter / setter函数来设置字符串属性。
类似的东西:
TMyPacket = class(TObject)
Private
FIDValue: TGUID;
FToIP: string;
FToPort: integer;
FSent: boolean;
FSentAt: TDateTime;
FAck: boolean;
FTimeOut: Cardinal;
FDataToSendSize: UINT64;
FDataToSend: AnsiString;
procedure SetID(const value: string);
function GetID: string;
public
constructor create;
destructor free;
property IDValue: TGUID read FID write FID;
published
property ID: string read GetID write SetID;
property ToIP: string read FToIP write FToIP;
property ToPort: integer read FToPort write FToPort
...
procedure TMyPacket.SetID(const value: string);
begin
fIDValue := StringToGUID(value);
end;
function TMyPacket.GetID: string;
begin
result := GUIDToString(fIDValue);
end;
然后序列化应该有效"ID":
字符串字段,您将在TGUID
公共属性中获得IVValue
值。