
正文
Delphi 10.2 Tokyo新增JSON类学习——TJsonSerializer
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
Delphi 10.3.2 for windows 7 编译通过,源码下载地址:
Tokyo 10.2新增类,效率更高更快
TJsonSerializer
需要引用单元:System.JSON.Serializers

unit uMain;interfaceuses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ComCtrls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Samples.Spin, Vcl.Buttons;type
TObj1 = class
private
F_i: Integer;
f_d: TDateTime;
f_s: string;
// f_a: TArray<string>;
public
constructor Create;
published
property field_s: string read f_s write f_s;
property field_i: Integer read F_i write F_i;
property field_d: TDateTime read f_d write f_d;
// property field_a: TArray<string> read f_a write f_a;
end; TfrmJSONText = class(TForm)
btn1: TButton;
mmolog: TMemo;
SpeedButton1: TSpeedButton;
seTestNumber: TSpinEdit;
lbl1: TLabel;
procedure FormCreate(Sender: TObject);
procedure btn1Click(Sender: TObject);
procedure Log(const S: string);
private
{ Private declarations }
public
{ Public declarations }
end;var
frmJSONText: TfrmJSONText;
TestNumber: Integer;implementationuses
System.Diagnostics
{$IF CompilerVersion>31.0}
, System.JSON.Serializers, System.JSON.Types
{$ENDIF}
;
{$R *.dfm}procedure TfrmJSONText.btn1Click(Sender: TObject);
{$IF CompilerVersion>31.0}
var
Foo: TObj1;
I: Integer;
sw: TStopwatch;
AJson: string;
Serializer: TJsonSerializer;
{$ENDIF}
begin
{$IF CompilerVersion>31.0}
TestNumber := seTestNumber.Value;
sw := TStopwatch.StartNew;
Serializer := TJsonSerializer.Create;
try
Serializer.DateTimeZoneHandling := TJsonDateTimeZoneHandling.Utc;
for I := to TestNumber - do
begin
Foo := TObj1.Create;
try
Foo.field_s := 'Hello World';
Foo.field_i := ;
Foo.field_d := Now;
AJson := Serializer.Serialize<TObj1>(Foo);
finally
Foo.Free;
end; end;
Log('TJsonSerializer.Serialize:' + sw.ElapsedMilliseconds.ToString + ' ms ' + AJson); sw := TStopwatch.StartNew;
for I := to TestNumber - do
begin
Foo := Serializer.Deserialize<TObj1>(AJson);
try
finally
Foo.Free;
end;
end;
Log('TJsonSerializer.Deserialize:' + sw.ElapsedMilliseconds.ToString + ' ms'); finally
FreeAndNil(Serializer);
end;
Log('=======================');
{$ENDIF}end;procedure TfrmJSONText.FormCreate(Sender: TObject);
const
// D2010~D10.3
DelphiIDEVers: array[..] of string = ('Delphi 2010', 'Delphi XE', 'Delphi XE2', 'Delphi XE3', 'Delphi XE4', 'Delphi XE5', 'Delphi XE6', 'Delphi XE7', 'Delphi XE8', 'Delphi 10 Seattle', 'Delphi 10.1 Berlin', 'Delphi 10.2 Tokyo', 'Delphi 10.3 Rio');
begin
{$IFDEF WIN64}
Caption := Caption + ' (64-bit)';
{$ENDIF}
{$IFDEF WIN32}
Caption := Caption + ' (32-bit)';
{$ENDIF} Caption := Caption + ' - ' + DelphiIDEVers[Trunc(CompilerVersion)];{$IF CompilerVersion<32.0} //版本小于Delphi 10.2 ,button Enabled false
btn1.Enabled := False;
{$ENDIF}
end;procedure TfrmJSONText.Log(const S: string);
begin
mmoLog.Lines.Add(S);
end;{ TObj1 }constructor TObj1.Create;
begin
inherited;
end;end.






