Last active
November 16, 2017 01:25
-
-
Save bonjin6770/26e0c4eddd1d7e0b95a9034361630d52 to your computer and use it in GitHub Desktop.
Delphi ObjectToJsonString
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just Sample Code.