delphi基於資料模型(data-model)JSON序列

delphi中间件發表於2024-03-31

delphi基於資料模型(data-model)JSON序列

需要DELPHI10.2以上版本才能支援。

1)實現JSON序列/還原的泛型模板

unit serialize;
/// <author>cxg 2024-1-11</author>

interface

uses
  system.Classes,
  System.SysUtils, System.JSON.Serializers;

type
  TSerial<T: record> = class
  public
    //還原
    class function unjson(const value: string): T; overload;
    class function unjson(const value: TStream): T; overload;
    class function unjson(const value: TBytes): T; overload;
    //序列
    class function json(const aRecord: T): string; overload;
  end;

function Stream2Raw(const aStream: TStream): RawByteString;
function bytes2raw(const aBytes: TBytes): RawByteString;

implementation

function bytes2raw(const aBytes: TBytes): RawByteString;
begin
  var len: Integer := Length(aBytes);
  SetLength(Result, len);
  Move(aBytes[0], Result[1], len);
end;

function Stream2Raw(const aStream: TStream): RawByteString;
begin
  SetLength(Result, aStream.Size);
  aStream.Position := 0;
  aStream.Read(Result[1], aStream.Size);
end;

class function TSerial<T>.json(const aRecord: T): string;
begin
  var s: TJsonSerializer := TJsonSerializer.Create;
  try
    Result := s.Serialize<T>(aRecord);
  finally
    s.Free;
  end;
end;

class function TSerial<T>.unjson(const value: string): T;
begin
  var s: TJsonSerializer := TJsonSerializer.Create;
  try
    Result := s.Deserialize<T>(value);
  finally
    s.free;
  end;
end;

class function TSerial<T>.unjson(const value: TStream): T;
begin
  Result := Self.unjson(UTF8Decode(Stream2Raw(value)));
end;

class function TSerial<T>.unjson(const value: TBytes): T;
begin
  Result := Self.unjson(UTF8Decode(bytes2raw(value)));
end;

end.

 2)定義“計量單位”的資料模型(data-model) 

unit danwei.model;
/// <author>cxg 2023-9-13</author>
interface

type      //定義 資料模型(data-model)
  Tdanwei = record
    unitid: string;
    unitname: string;
  end;

implementation

end.

  3)呼叫示例

table := serialize.TSerial<TTable<T>>.unjson(TStream(req.Body));  //還原json string--->record

res.Send(TSerial<TTable<T>>.json(table));   //JSON序列 send json string

  

相關文章