delphi JSON序列化(五)

关于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"}

 

热门相关:霍先生结婚吧   霍先生结婚吧   锦衣当国   锦绣医妃之庶女凰途   霸宠天下:腹黑帝君妖娆后