delphi基于数据模型(data-model)JSON序列
delphi基于数据模型(data-model)JSON序列
需要DELPHI10.2以上版本才能支持。
1)实现JSON序列/还原的泛型模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | 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)
1 2 3 4 5 6 7 8 9 10 11 12 13 | unit danwei.model; /// <author>cxg 2023-9-13</author> interface type //定义 数据模型(data-model) Tdanwei = record unitid: string ; unitname: string ; end; implementation end. |
3)调用示例
1 2 3 | table := serialize.TSerial<TTable<T>>.unjson(TStream(req.Body)); //还原json string--->record res.Send(TSerial<TTable<T>>.json(table)); //JSON序列 send json string |
本文来自博客园,作者:{咏南中间件},转载请注明原文链接:https://www.cnblogs.com/hnxxcxg/p/18107144
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步