mormot json主从表

Posted 咏南中间件和开发框架

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mormot json主从表相关的知识,希望对你有一定的参考价值。

mormot json主从表

//cxg 2021-6-2  mormot json主从表

unit service.tables;

interface

uses
  mormot, sysutils, yn.log, yn.Unidac, yn.UnidacPool, SynCrtSock, Classes,
  SynCommons, SynVirtualDataSet;

type
  TMasterTable = class(mORMot.TSQLRecord)  //主表
  private
    fBillId: RawUTF8;
    fOperator: RawUTF8;
  published
    property BillId: RawUTF8 read fBillId write fBillId;
    property operator: RawUTF8 read fOperator write fOperator;
  end;

  TDetailTable = class(mORMot.TSQLRecord) //从表
  private
    fProductId: RawUTF8;
    fProductName: RawUTF8;
  published
    property ProductId: RawUTF8 read fProductId write fProductId;
    property ProductName: RawUTF8 read fProductName write fProductName;
  end;

function serial(const url: sockstring): SockString;
procedure deserial(const json: string);

implementation

procedure deserial(const json: string);
var
  mtable: TMasterTable;
  dtable: TDetailTable;
  js: TDocVariantData;
  m, d, tmp: string;
begin
  js.InitJSON(json);
  m := utf8toansi(js.GetValueByPath([\'mtable\']));  //主表
  mtable := TMasterTable.CreateAndFillPrepare(m);
  while mtable.FillOne do
  begin
    tmp := mtable.BillId;
    tmp := mtable.operator;
  end;
  mtable.Free;

  d := utf8toansi(js.GetValueByPath([\'dtable\']));   //从表
  dtable := TDetailTable.CreateAndFillPrepare(d);
  while dtable.FillOne do
  begin
    tmp := dtable.ProductId;
    tmp := dtable.ProductName;
  end;
  dtable.Free;
end;

function serial(const url: sockstring): SockString;
//get url: /tables/{accountno}
var
  i: Integer;
  mTable: TMasterTable;
  dTable: TDetailTable;
  m, d: string;
  jo: Variant;
begin
  m := \'[\';
  for i := 1 to 2 do //生成主表数据
  begin
    TMasterTable.AutoFree(mTable);
    mTable.BillId := inttostr(i);
    mtable.operator := \'name\' + inttostr(i);
    if i < 2 then
      m := m + mtable.GetJSONValues(true, false, soselect) + \',\'
    else
      m := m + mtable.GetJSONValues(true, false, soselect);
  end;
  m := m + \']\';
  
  d := \'[\';
  for i := 1 to 2 do //生成从表数据
  begin
    TDetailTable.AutoFree(dTable);
    dTable.ProductId := inttostr(i);
    dtable.ProductName := \'p\' + inttostr(i);
    if i < 2 then
      d := d + dtable.GetJSONValues(true, false, soselect) + \',\'
    else
      d := d + dtable.GetJSONValues(true, false, soselect);
  end;
  d := d + \']\';
  TDocVariant.New(jo);
  jo.mTable := _JSon(m);  //生成主从表数据
  jo.dTable := _JSon(d);
  result := ansitoutf8(VariantSaveJSON(jo));
  //{"mTable":[{"BillId":"1","operator":"name1"},{"BillId":"2","operator":"name2"}],"dTable":[{"ProductId":"1","ProductName":"p1"},{"ProductId":"2","ProductName":"p2"}]}
end;

end.

  

以上是关于mormot json主从表的主要内容,如果未能解决你的问题,请参考以下文章

转:Delphi语言最好的JSON代码库 mORMot学习笔记1

Delphi语言最好的JSON代码库 mORMot学习笔记1

论MORMOT序列的JSON格式

mormot数据库连接+查询+序列为JSON

如何使用mormot将通用TList序列化为JSON

mormot orm rest注意事项