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
标签:function,end,delphi,value,class,JSON,const,unjson,数据模型 From: https://www.cnblogs.com/hnxxcxg/p/18107144