Skip to content

Instantly share code, notes, and snippets.

@bonjin6770
Last active November 16, 2017 01:25
Show Gist options
  • Save bonjin6770/26e0c4eddd1d7e0b95a9034361630d52 to your computer and use it in GitHub Desktop.
Save bonjin6770/26e0c4eddd1d7e0b95a9034361630d52 to your computer and use it in GitHub Desktop.
Delphi ObjectToJsonString
unit MyInfo;
interface
type
TMyInfo = class
private
FName: string;
FAge: integer;
public
property Name: string read FName Write FName;
property Age: integer read FAge Write FAge;
end;
implementation
end.
// sample code
// Delphi XE5
uses
REST.JSON;
procedure TfmMainForm.btnSaveClick(Sender: TObject);
var
info: TMyInfo;
sl: TStringList;
jsonString: string;
begin
info := TMyInfo.Create;
try
info.Name := edtName.Text;
info.Age := StrToInt(edtAge.Text);
jsonString := TJson.ObjectToJsonString(info);
finally
FreeAndNil(info);
end;
memJsonString.Text := jsonString;
sl := TStringList.Create;
try
sl.Add(jsonString);
sl.SaveToFile(edtFileName.Text);
finally
FreeAndNil(sl);
end;
end;
procedure TfmMainForm.btnLoadClick(Sender: TObject);
var
info: TMyInfo;
sl: TStringList;
jsonString: string;
begin
// Load File
sl := TStringList.Create;
try
sl.LoadFromFile(edtFileName.Text);
jsonString := sl.Text;
finally
FreeAndNil(sl);
end;
memJsonString.Text := jsonString;
try
info := TJson.JsonToObject<TMyInfo>(jsonString);
edtName.Text := info.Name;
edtAge.Text := IntToStr(info.Age);
finally
FreeAndNil(info);
end;
end;
@bonjin6770
Copy link
Author

Just Sample Code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment