delphi 自带的JSON序列化类

发布时间 2023-08-09 17:05:54作者: jjw
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
  System.JSON.Serializers, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
type
  TRecA = record
    stringValue: string;
    datetimeValue: TDateTime;
    integerValue: Integer;
    doubleValue: Double;
  end;

  TRecB = record
    stringValue: string;
    datetimeValue: TDateTime;
    integerValue: Integer;
    doubleValue: Double;
  end;

  TRecAB = record
    A: TRecA;
    B: TRecB;
  end;
begin
  var AB: TRecAB;
  AB.A.stringValue := 'hello world';
  AB.A.datetimeValue := Now;
  AB.A.integerValue := 123;
  AB.A.doubleValue := 3.1415926;

  AB.B.stringValue := 'HELLO WORLD';
  AB.B.datetimeValue := Now;
  AB.B.integerValue := 666;
  AB.B.doubleValue := 3.1415927;

  var Arr: TArray<TRecAB>;

  SetLength(Arr, 1);

  Arr[0] := AB;

  var s := TJsonSerializer.Create;
  Memo1.Text := s.Serialize<TArray<TRecAB>>(Arr);

  var d := TJsonSerializer.Create;
  var EmptyArray: TArray<Integer> := d.Deserialize<TArray<Integer>>('[]');
  Caption := Length(EmptyArray).ToString;
end;

end.

记不清什么时候有的,个人感觉还是很好用的. 可以控制 序列化属性,字段(私有)等。