delphi类(记录)同json互相转换

delphi类(记录)同json互相转换

delphi Tokyo 10.2新增TJsonSerializer类,效率更高更快。

/// <author>cxg 2021-4-4</author>
///Tokyo 10.2新增TJsonSerializer类,效率更高更快。

unit Unit2;

interface

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

type
  TUser = record
    name: string;
    age: Integer;
  end;

  TPerson = class
  private
    FName: string;
    FAge: Integer;
  public
    constructor Create(const Name: String; Age: Integer);
    property Name: string read FName write FName;
    property Age: Integer read FAge write FAge;
  end;

  TForm2 = class(TForm)
    Memo1: TMemo;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    Button4: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  private
    { Private declarations }
    persons: TObjectList<TPerson>;
    users: TArray<TUser>;
  public
    { Public declarations }
  end;

var
  Form2: TForm2;

implementation

{$R *.dfm}

{ TPerson }

constructor TPerson.Create(const Name: String; Age: Integer);
begin
  FName := Name;
  FAge := Age;
end;

procedure TForm2.Button1Click(Sender: TObject);
//class2json
begin
  persons := TObjectList<TPerson>.Create;
  persons.Add(TPerson.Create('张三', 40));
  persons.Add(TPerson.Create('李四', 38));
  var serial: TJsonSerializer := TJsonSerializer.Create;
  Memo1.Text := serial.Serialize<TObjectList<TPerson>>(persons);  //{"FOwnsObjects":true,"FListHelper":[{"FName":"张三","FAge":40},{"FName":"李四","FAge":38}],"FComparer":{}}
  serial.Free;
  persons.Free;
end;

procedure TForm2.Button2Click(Sender: TObject);
//json2class
begin
  var serial: TJsonSerializer := TJsonSerializer.Create;
  persons := serial.Deserialize<TObjectList<TPerson>>(Memo1.Text);
  for var person: TPerson in persons do
    Memo1.Lines.Add(person.Name);         //张三  李四
  serial.Free;
  persons.Free;
end;

procedure TForm2.Button3Click(Sender: TObject);
//record2json
begin
  SetLength(users, 2);
  var user: TUser;
  user.name := '王五';
  user.age := 1;
  users[0] := user;
  var user2: TUser;
  user2.name := '赵六';
  user2.age := 2;
  users[1] := user2;
  var serial: TJsonSerializer := TJsonSerializer.Create;
  Memo1.Text := serial.Serialize<TArray<TUser>>(users);    //[{"name":"王五","age":1},{"name":"赵六","age":2}]
  serial.Free;
end;

procedure TForm2.Button4Click(Sender: TObject);
//json2record
begin
  var serial: TJsonSerializer := TJsonSerializer.Create;
  users := serial.Deserialize<TArray<TUser>>(Memo1.Text);
  for var user: TUser in users do
    memo1.Lines.Add(user.name);
  serial.Free;
end;

end.

  

上一篇:ESP8266定时器


下一篇:并发编程-重排序