jjw

写给自己的博客。 记录学习的点滴以备查。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

delphi JSON序列化(五)

Posted on 2024-01-10 17:18  jjw  阅读(40)  评论(0编辑  收藏  举报

关于TJSONConverters的使用

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Buttons, Rest.JSON.Types, Rest.JsonReflect;

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

  TValueObject = class
  private
    FValue: string;
    FCreateTime: TDateTime;
  public
    constructor Create;
    property Value: string read FValue write FValue;
    property CreateTime: TDateTime read FCreateTime write FCreateTime;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses
  REST.Json, System.Generics.Collections;


procedure TForm1.FormCreate(Sender: TObject);
begin
  var ce := TConverterEvent.Create(TValueObject, 'FValue'); // 使用此构造函数
  ce.StringConverter := function(Data: TObject; Field: string): string
    begin
      Result := 'haha';
    end;

  TJSONConverters.AddConverter(ce);

  Memo1.Text := TJson.ObjectToJsonString(TValueObject.Create);
end;

{ TValueObject }

constructor TValueObject.Create;
begin
  inherited Create;
  FValue := 'test value';
  FCreateTime := Now;
end;

end.

结果: {"value":"haha","createTime":"2024-01-10T17:15:33.588Z"}

注:REST. XXX单元的序列化类感觉不好用, 想把TObjectList<TPerson>序列化没有好的切处点。