关于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>序列化没有好的切处点。