说明:
这里实现的JSON构建类TJSONBuilder继承自Delphi 10.1开始提供的TJSONObjectBuilder。TJSONBuilder最多只允许存在一个实例,每次执行TJSONBuilder.Create时都会自动清除掉上一次创建的实例,程序关闭时也会自动清除最后创建的实例, 因此使用这个类不需要考虑内存释放的问题。
使用示例:
uses uJSONBuilder, System.JSON.Builders;
procedure TForm1.ButtonShowClick(Sender: TObject);
begin
TJSONBuilder.Create
.BeginObject //注意这并不是什么delphi新语法,而是普通的链式写法而已,如A.B('bigcat').C.D...
.Add('touser', 'BigCat')
.Add('msgtype', 'text')
.BeginObject('消息')
.Add('title' , '快递通知')
.Add('content', '你的快递已到,请携带工卡前往邮件中心领取。')
.EndObject
.BeginArray('快递物品清单')
.BeginObject
.Add('图书数', 3)
.EndObject
.BeginObject
.Add('手机数', 3)
.EndObject
.EndArray
.Add('agentid', 1000002)
.EndObject;
ShowMessage(TJSONBuilder.JSON);
TJSONBuilder.Create
.BeginObject
.BeginArray('考试成绩')
.BeginObject
.Add('姓名', '张三')
.Add('成绩', 100.0 )
.EndObject
.BeginObject
.Add('姓名', '李四')
.Add('成绩', 59.9 )
.EndObject
.EndArray
.EndObject;
ShowMessage(TJSONBuilder.JSON);
end;
==========================================================================================
类的源代码:
unit uJSonBuilder;
interface
uses System.Classes, System.SysUtils, System.JSON, System.JSON.Types,
System.JSON.Writers, System.JSON.Readers, System.JSON.Builders;
type
TJSONBuilder = class(TJSONObjectBuilder) //单实例类
private
StringBuilder : TStringBuilder;
StringWriter : TStringWriter;
JSONTextWriter: TJsonTextWriter;
class var FJSONBuilder: TJSONBuilder;
class function GetJSON: string; static;
public
class property JSON: String read GetJSON;
constructor Create(const AFormatting: TJsonFormatting = TJsonFormatting.None);
destructor Destroy; override;
end;
implementation
constructor TJSONBuilder.Create(const AFormatting: TJsonFormatting);
begin
if FJSONBuilder <> nil then
FJSONBuilder.Free; //只保持单实例
StringBuilder := TStringBuilder.Create;
StringWriter := TStringWriter.Create(StringBuilder);
JSONTextWriter := TJsonTextWriter.Create(StringWriter);
JSONTextWriter.Formatting := AFormatting;
inherited Create(JSONTextWriter);
FJSONBuilder := Self;
end;
destructor TJSONBuilder.Destroy;
begin
inherited;
StringBuilder.Free;
StringWriter.Free;
JSONTextWriter.Free;
FJSONBuilder := nil;
end;
class function TJSONBuilder.GetJSON: string;
begin
if FJSONBuilder = nil then
Result := ''
else
Result := FJSONBuilder.StringBuilder.ToString;
end;
initialization
TJSONBuilder.FJSONBuilder := nil;
finalization
if TJSONBuilder.FJSONBuilder <> nil then
TJSONBuilder.FJSONBuilder.Free;
end.