其他分享
首页 > 其他分享> > json主从表

json主从表

作者:互联网

json主从表

//cxg 2021-6-1 主从表json

unit service.tables;

interface

uses
  system.JSON.Serializers, system.JSON,
  system.Generics.Collections, sysutils, Classes;

type
  TMasterTable = record
    billid: Integer;
    operate: string;
  end;

  TDetailTable = record
    productid: Integer;
    productname: string;
  end;

var MasterTables: TArray<TMasterTable>;
var DetailTables: TArray<TDetailTable>;

function getJson(const url: string): string;
procedure setJson(const v: string);

implementation

procedure setJson(const v: string);
begin
  var jo: TJSONObject := TJSONObject.ParseJSONValue(v) as TJSONObject;
  var ja: TJSONArray := TJSONArray(jo.GetValue('主表'));
  var s: string := ja.ToString;  //[{"billid":0,"operate":"name0"},{"billid":1,"operate":"name1"}]
  var serial: TJsonSerializer := TJsonSerializer.Create;
  MasterTables := serial.Deserialize<TArray<TMasterTable>>(s);
  s := MasterTables[0].operate;  //name0
  serial.Free;
  jo.Free;
end;

function getJson(const url: string): string;
//主从表 get url: /dal/bills/{accountno}
begin
  try
    try
      SetLength(MasterTables, 2);      //生成主表数据
      var i: Integer;
      for i := 0 to 1 do
      begin
        MasterTables[i].billid := i;
        MasterTables[i].operate := 'name' + i.ToString;
      end;
      SetLength(DetailTables, 2);
      for i := 0 to 1 do           //生成从表数据
      begin
        DetailTables[i].productid := i;
        DetailTables[i].productname := 'name' + i.ToString;
      end;
      var serial: TJsonSerializer := TJsonSerializer.Create;
      var jo: TJSONObject := TJSONObject.Create;
      var ja: TJSONArray := TJSONObject.ParseJSONValue(serial.Serialize<TArray<TMasterTable>>(MasterTables)) as TJSONArray;
      jo.AddPair('主表', ja);
      ja := TJSONObject.ParseJSONValue(serial.Serialize<TArray<TDetailTable>>(DetailTables)) as TJSONArray;
      jo.AddPair('从表', ja);
      Result := jo.ToString; //{"主表":[{"billid":0,"operate":"name0"},{"billid":1,"operate":"name1"}],"从表":[{"productid":0,"productname":"name0"},{"productid":1,"productname":"name1"}]}
      jo.free;
      serial.free;
    except
      on E: Exception do
      begin
        result := '{"异常":"' + e.Message + '"}';
      end;
    end;
  finally

  end;
end;

end.

  

标签:end,string,json,jo,var,serial,主从,MasterTables
来源: https://www.cnblogs.com/hnxxcxg/p/14839669.html