我正在尝试使用mORMot框架将TObject序列化为JSON。不幸的是,结果总是空的。
我尝试序列化的类是:
type ApmTime = class(TObject)
private
function currentTime() : String;
published
property Current_time: String read currentTime;
public
constructor Create;
end;
constructor ApmTime.Create;
begin
inherited;
end;
function ApmTime.currentTime() : String;
begin
result := TimeToStr(Now);
end;在SynCommons中定义了相应的mORMot方法:
currentTime := ApmTime.Create;
Write(ObjectToJSON(currentTime, [woFullExpand]));这总是返回null。在单步执行TTextWriter.WriteObject (位于单元SynCommons中)之后,以下代码片段似乎就是将结果json设置为空的地方:
if not(woFullExpand in Options) or
not(Value.InheritsFrom(TList)
{$ifndef LVCL} or Value.InheritsFrom(TCollection){$endif}) then
Value := nil;
if Value=nil then begin
AddShort('null');
exit;我一直期待着这样的事情:
{
"Current_time" : "15:04"
}发布于 2018-02-18 08:03:46
尝试向发布的属性添加写操作。
property Current_time: String read currentTime write SetCurrentTime. 只读属性未序列化。另外,ApmTime应该基于TPersistent
type
ApmTime = class(TPersistent)发布于 2019-09-25 23:10:32
昨天遇到了这个问题,并弄清楚了发生了什么,所以为了将来的人们也能在这个问题上犯错误:
如果您只将SynCommons.pas添加到uses子句中,那么默认的DefaultTextWriterJSONClass将被设置为TTextWriter,它只支持序列化特定的类类型,而不支持任意的类/对象。在设置了此默认值的SynCommons.pas中,请参阅以下行:
var
DefaultTextWriterJSONClass: TTextWriterClass = TTextWriter;现在,为了支持将任意对象序列化为JSON,需要将这个全局变量从默认的TTextWriter更改为TJSONSerializer。
这个类是在mORMot.pas中定义的,实际上,如果您将mORMot.pas添加到uses子句中,它的初始化将覆盖上面的默认值,并将TJSONSerializer设置为新的默认值。
如果你仔细阅读,可以在SynCommons.pas中记录这种行为,例如,查看"SetDEfaultJSONClass()“类方法的注释:
// you can use this method to override the default JSON serialization class
// - if only SynCommons.pas is used, it will be TTextWriter
// - but mORMot.pas initialization will call it to use the TJSONSerializer
// instead, which is able to serialize any class as JSON
class procedure SetDefaultJSONClass(aClass: TTextWriterClass);因此,简而言之:要解决您的问题,只需在您应该已经拥有的SynCommons.pas子句中添加mORMot.pas即可。
https://stackoverflow.com/questions/48847065
复制相似问题