首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用mormot自动将TObject序列化为JSON

使用mormot自动将TObject序列化为JSON
EN

Stack Overflow用户
提问于 2018-02-18 07:49:32
回答 2查看 1.1K关注 0票数 2

我正在尝试使用mORMot框架将TObject序列化为JSON。不幸的是,结果总是空的。

我尝试序列化的类是:

代码语言:javascript
复制
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方法:

代码语言:javascript
复制
currentTime := ApmTime.Create;
Write(ObjectToJSON(currentTime, [woFullExpand]));

这总是返回null。在单步执行TTextWriter.WriteObject (位于单元SynCommons中)之后,以下代码片段似乎就是将结果json设置为空的地方:

代码语言:javascript
复制
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;

我一直期待着这样的事情:

代码语言:javascript
复制
{
  "Current_time" : "15:04"
}
EN

回答 2

Stack Overflow用户

发布于 2018-02-18 08:03:46

尝试向发布的属性添加写操作。

代码语言:javascript
复制
property Current_time: String read currentTime write SetCurrentTime. 

只读属性未序列化。另外,ApmTime应该基于TPersistent

代码语言:javascript
复制
type 
  ApmTime = class(TPersistent)
票数 1
EN

Stack Overflow用户

发布于 2019-09-25 23:10:32

昨天遇到了这个问题,并弄清楚了发生了什么,所以为了将来的人们也能在这个问题上犯错误:

如果您只将SynCommons.pas添加到uses子句中,那么默认的DefaultTextWriterJSONClass将被设置为TTextWriter,它只支持序列化特定的类类型,而不支持任意的类/对象。在设置了此默认值的SynCommons.pas中,请参阅以下行:

代码语言:javascript
复制
var
  DefaultTextWriterJSONClass: TTextWriterClass = TTextWriter;

现在,为了支持将任意对象序列化为JSON,需要将这个全局变量从默认的TTextWriter更改为TJSONSerializer。

这个类是在mORMot.pas中定义的,实际上,如果您将mORMot.pas添加到uses子句中,它的初始化将覆盖上面的默认值,并将TJSONSerializer设置为新的默认值。

如果你仔细阅读,可以在SynCommons.pas中记录这种行为,例如,查看"SetDEfaultJSONClass()“类方法的注释:

代码语言:javascript
复制
// 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即可。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48847065

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档