mormot2 JSON 序列化与反序列化操作
mormot2 json 序列化与反序列化操作
本文非完全原创,本文部分内容来自博客园,作者:{咏南中间件}
以下功能利用mORMot2实现 记录和对象的JSON序列化和反序列化。
nit hi.JSONSerializer;
{$mode delphi}{$H+}
interface
uses
Classes, SysUtils,
Generics.Collections,
mormot.core.base,
mormot.core.json,
mormot.core.variants,
mormot.core.Text;
type
{ TJsonSerializer }
TJsonSerializer = class
class function RecordToJson<T>(const aRec: T; useIndent: boolean = False; EnumAsText: boolean = False): rawutf8;
overload;
class function ObjectToJson(const aObj: TObject; useIndent: boolean = False; EnumAsText: boolean = False): rawutf8;
overload;
class function JsonToRecord<T>(const aJsonStr: rawutf8): T; overload;
class procedure JsonToObject(const aJsonStr: rawutf8; aObj: TObject); overload;
end;
implementation
{ TJsonSerializer }
class function TJsonSerializer.ObjectToJson(const aObj: TObject; useIndent: boolean = False;
EnumAsText: boolean = False): rawutf8;
var
dict: IDocDict;
begin
dict := DocDictFrom(ObjectToVariant(aObj, EnumAsText));
if useIndent then
Result := dict.ToJson(jsonHumanReadable)
else
Result := dict.ToJson;
//上面代码刚觉清晰一些
{
// 与上面功能等效
// Result := mormot.core.Text.ObjectToJson(aObj);
// if useIndent then
// Result := JsonReformat(Result, jsonHumanReadable);
}
end;
class function TJsonSerializer.RecordToJson<T>(const aRec: T; useIndent: boolean = False;
EnumAsText: boolean = False): rawutf8;
begin
//采用的传统mORMot1方案。
Result := mormot.core.json.RecordSaveJson(aRec, TypeInfo(T), EnumAsText);
if useIndent then
Result := JsonReformat(Result, jsonHumanReadable);
end;
class procedure TJsonSerializer.JsonToObject(const aJsonStr: rawutf8; aObj: TObject);
begin
mormot.core.json.ObjectLoadJson(aObj, aJsonStr);
end;
class function TJsonSerializer.JsonToRecord<T>(const aJsonStr: rawutf8): T;
begin
mormot.core.json.RecordLoadJson(Result, aJsonStr, TypeInfo(T));
end;
end.