如何在mORMot中用ObjectToJSON将空字符串字段序列化为null?
在mORMot中将空字符串序列化为JSON null的解决方案
问题场景
在FreePascal中使用mORMot框架序列化对象到JSON时,字符串字段为空时默认输出空字符串"",但需要将其转为JSON的null值。相关代码及输出如下:
原代码
uses SysUtils, SynCommons; type TPersonClass = class(TSynPersistent) private FName: String; FAge: Integer; published property Name: String read FName write FName; property Age: Integer read FAge write FAge; end; var Person: TPersonClass; JSON: RawUTF8; begin Person := TPersonClass.Create; try Person.Name := ''; // 需要输出为null Person.Age := 30; JSON := ObjectToJSON(Person, [woHumanReadable]); Writeln(JSON); finally Person.Free; end; end.
当前输出
{ "Name": "", "Age": 30 }
期望输出
{ "Name": null, "Age": 30 }
解决方案
方法1:使用全局序列化选项woEmptyStringAsNil
mORMot的ObjectToJSON函数支持通过序列化选项控制空字符串的处理,添加woEmptyStringAsNil即可将所有空字符串字段序列化为null。
修改后的代码:
uses SysUtils, SynCommons; type TPersonClass = class(TSynPersistent) private FName: String; FAge: Integer; published property Name: String read FName write FName; property Age: Integer read FAge write FAge; end; var Person: TPersonClass; JSON: RawUTF8; begin Person := TPersonClass.Create; try Person.Name := ''; // 现在会输出为null Person.Age := 30; // 添加woEmptyStringAsNil选项 JSON := ObjectToJSON(Person, [woHumanReadable, woEmptyStringAsNil]); Writeln(JSON); finally Person.Free; end; end.
方法2:针对单个字段使用Nullable<string>类型
如果不需要全局生效,仅针对特定字段控制null输出,可以将字段类型改为Nullable<string>,当字段值为Null时会序列化为JSON的null。
示例代码:
uses SysUtils, SynCommons, SynCrossPlatform; // 引入Nullable相关单元 type TPersonClass = class(TSynPersistent) private FName: Nullable<string>; FAge: Integer; published property Name: Nullable<string> read FName write FName; property Age: Integer read FAge write FAge; end; var Person: TPersonClass; JSON: RawUTF8; begin Person := TPersonClass.Create; try Person.Name := Null; // 直接赋值为Null,输出为null Person.Age := 30; JSON := ObjectToJSON(Person, [woHumanReadable]); Writeln(JSON); finally Person.Free; end; end.
最佳实践
- 如果项目中所有空字符串都需要转为
null,优先使用woEmptyStringAsNil全局选项,配置简单且统一。 - 如果仅部分字段需要特殊处理,使用
Nullable<string>类型可以更精准地控制字段的序列化行为,同时能明确区分"空字符串"和"无值"两种状态。
内容的提问来源于stack exchange,提问作者kvisthor
相关产品推荐
相关产品推荐

