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

  

posted @   delphi中间件  阅读(191)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-03-31 delphi json生成和解析
2019-03-31 FDMEMTABLE将修改后的数据序列为JSON
2019-03-31 firedac数据集数据序列为JSON
2017-03-31 ubuntu允许mysql远程连接
2016-03-31 咏南中间件集群
点击右上角即可分享
微信分享提示