mormot2 json操作
mormot2 json操作
unit mormot2.json.serial; /// <author>cxg 2023-6-4</author> {$I def.inc} interface uses mormot.core.buffers, mormot.core.text, mormot.core.json, mormot.core.base, Classes, SysUtils; type { TSerial } TSerial = class class function marshal<T>(const aRec: T): rawutf8; overload; class function marshal(const aObj: TObject): rawutf8; overload; class function unmarshal<T>(const json: rawutf8): T; overload; class procedure unmarshal(const json: rawutf8; aObj: TObject); overload; end; implementation { TSerial } class function TSerial.marshal(const aObj: TObject): rawutf8; begin Result := mormot.core.text.ObjectToJson(aObj); end; class function TSerial.marshal<T>(const aRec: T): rawutf8; begin result := mormot.core.json.RecordSaveJson(aRec, TypeInfo(T)); end; class procedure TSerial.unmarshal(const json: rawutf8; aObj: TObject); begin mormot.core.json.ObjectLoadJson(aObj, json); end; class function TSerial.unmarshal<T>(const json: rawutf8): T; begin mormot.core.json.RecordLoadJson(result, json, TypeInfo(T)); end; end.
unit Unit2; interface uses // mormot.crypt.core, mormot2.json.serial, mormot.orm.core, mormot.core.buffers, mormot.core.text, mormot.core.variants, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TTest = record //结构体 id: Integer; name: string; end; TTests = record msg: string; t: tarray<TTest>; end; TObj = class private fid: integer; fname: string; published property id: integer read fid write fid; property name: string read fname write fname; end; TForm2 = class(TForm) Button1: TButton; Button2: TButton; Memo1: TMemo; Button3: TButton; Button4: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form2: TForm2; implementation {$R *.dfm} procedure TForm2.Button1Click(Sender: TObject); //record2json var tt: ttests; begin setlength(tt.t, 1); tt.msg := '测试'; tt.t[0].id := 1; tt.t[0].name := '名字'; memo1.Text := TSerial.marshal<TTests>(tt); end; procedure TForm2.Button2Click(Sender: TObject); //json2record var tt: TTests; begin tt := TSerial.unmarshal<TTests>(memo1.text); ShowMessage(tt.t[0].name); //名字 end; procedure TForm2.Button3Click(Sender: TObject); //obj2json var o: TObj; begin o := TObj.Create; o.id := 11; o.name := '名字'; Memo1.Text := TSerial.marshal(o); o.Free; end; procedure TForm2.Button4Click(Sender: TObject); //json2obj var o: TObj; begin o := TObj.Create; tserial.unmarshal(memo1.Text, o); showmessage(o.name); o.Free; end; end.
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/17232921.html