在高版本的 Delphi 中,实现序列化和反序列化非常简单。然而,在 Delphi 7 中,这个过程仍然需要一些额外的努力。为了简化这个问题,我花了一些时间封装了一个支持序列化和反序列化的 JSON 解析库。
type
{$M+}
TStartupParameters = class
private
FAccount: String;
FPassword: String;
FServerName: String;
FChannel: String;
FTaskName: String;
FWindowHandle: HWND;
public
constructor Create;
destructor Destroy; override;
published
property Account: String read FAccount write FAccount;
property Password: String read FPassword write FPassword;
property ServerName: String read FServerName write FServerName;
property Channel: String read FChannel write FChannel;
property TaskName: String read FTaskName write FTaskName;
property WindowHandle: HWND read FWindowHandle write FWindowHandle;
end;
{$M-}
function ObjectToJson: string;
var
obj: ISuperObject;
LStartupParameters: TStartupParameters;
begin
LStartupParameters := TStartupParameters.Create;
LStartupParameters.FAccount:= 'test';
LStartupParameters.FPassword:= '123456';
obj := TOldRttiMarshal.ToJson(LStartupParameters);
Result:= obj.AsJson;
end;
function JsonToObject(JsonString: string): string;
begin
StartupParameters := TStartupParameters(TOldRttiUnMarshal.FromJson(TStartupParameters, JsonString));
Result:= 'Account: ' + StartupParameters.Account +#13#10+ 'Password: ' + StartupParameters.Password;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Memo1.Lines.Add(ObjectToJson);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
JsonToObject(Memo1.Text);
Memo2.Lines.Add(JsonToObject(Memo1.Text));
end;