qjson中把记录或类型或泛型数组转换为json字符串

我一直都在寻找各种业务功能的最简单写法,用减法的模式来开发软件。如果有比我的写法更简单的方法,请留言告知。

unit Unit4;

interface

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

type
  TForm4 = class(TForm)
    btn1: TButton;
    Memo1: TMemo;
    lbl1: TLabel;
    btn2: TButton;
    procedure btn1Click(Sender: TObject);
    procedure btn2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

/// <summary>
/// 新手留意,一定要定义在implementation关键词的上方.
/// </summary>
type TRenLei = record
  name: string;
  age: Integer;
  sex: Boolean;
end;


var
  Form4: TForm4;

implementation

{$R *.dfm}

uses qjson;

procedure TForm4.btn1Click(Sender: TObject);
var
  ARenLei: TRenLei;
  MyQj: TQJson;
begin
  MyQj := TQJson.Create;
  try
    //这个例子比较好理解
    ARenLei.name := '奥巴马';
    ARenLei.age := 1;
    ARenLei.sex := True;

    MyQj.FromRecord<TRenLei>(ARenLei);
    Memo1.Lines.Clear;
    Memo1.Lines.Add(MyQj.AsJson);
  finally
    MyQj.Free;
  end;
end;

procedure TForm4.btn2Click(Sender: TObject);
var
  RenLeiArray: TArray<TRenLei>;
  MyQj: TQJson;
begin
  MyQj := TQJson.Create;
  try
    SetLength(RenLeiArray,2);
    with RenLeiArray[0] do
    begin
      name := '拜登';
      age := 1;
      sex := True;
    end;
    with RenLeiArray[1] do
    begin
      name := '希拉里';
      age := 2;
      sex := False;
    end;

    //这里不是很好理解了,我也不理解,这里用TArray<TRenLei>就可以把泛型数组转换为Json,谁知道原理的请下方留言。
    MyQj.FromRecord<TArray<TRenLei>>(RenLeiArray);
    Memo1.Lines.Clear;
    Memo1.Lines.Add(MyQj.AsJson);
  finally
    MyQj.Free;
  end;
end;

end.

 

分享到: