mormot json序列(还原)

mormot json序列(还原)

/// <author>cxg 2021-5-28</author>
/// delphi7 + mormot1.18
/// json序列\还原
(* people.json
[
{"RowID":3,"FirstName":"咏南","LastName":"Rachmaninoff","Data":"?w6l6w6di","YearOfBirth":1800,"YearOfDeath":1943},
{"RowID":4,"FirstName":"中间件","LastName":"Dumas","Data":"?w6nDp2I=","YearOfBirth":1801,"YearOfDeath":1870},
{"RowID":7,"FirstName":"rest","LastName":"Huxley","Data":"?w6nDoA==","YearOfBirth":1802,"YearOfDeath":1963},
]
*)

unit Unit1;

interface

uses
  mORMot, SynCommons, Contnrs,
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
    fFileName: string;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

type
  TSQLRecordPeople = class(TSQLRecord)
  private
    fData: TSQLRawBlob;
    fFirstName: RawUTF8;
    fLastName: RawUTF8;
    fYearOfBirth: integer;
    fYearOfDeath: word;
  published
    property FirstName: RawUTF8 read fFirstName write fFirstName;
    property LastName: RawUTF8 read fLastName write fLastName;
    property Data: TSQLRawBlob read fData write fData;
    property YearOfBirth: integer read fYearOfBirth write fYearOfBirth;
    property YearOfDeath: word read fYearOfDeath write fYearOfDeath;
  end;

procedure TForm1.Button1Click(Sender: TObject);
//从json还原对象1
var json: RawUTF8;
    i: integer;
    list: TSQLTableJSON;
    doc: TObjectList;
    p: TSQLRecordPeople;
begin
  json := StringFromFile(fFileName);
  list := TSQLTableJSON.Create('',pointer(json),length(json));
  doc := list.ToObjectList(TSQLRecordPeople);
  list.Free;
  json := '';
  for i := 0 to doc.Count-1 do
  begin
    p := TSQLRecordPeople(doc.List[i]);
    Memo1.Lines.Add(Utf8ToAnsi(p.fFirstName));
  end;
  doc.Free;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  fFileName := 'people.json';
  Memo1.Clear;
end;

procedure TForm1.Button2Click(Sender: TObject);
//从json还原对象2
var p: TSQLRecordPeople;
    json: RawUTF8;
begin
  json := StringFromFile(fFileName);
  p := TSQLRecordPeople.CreateAndFillPrepare(json);
  json := '';
  while p.FillOne do
  begin
    Memo1.Lines.Add(Utf8ToAnsi(p.FirstName));
  end;
  p.Free;
end;

end.

  

posted @ 2021-05-28 13:05  delphi中间件  阅读(254)  评论(0编辑  收藏  举报