SOLUTION: ask ChatGPT!
QUESTION:
Please use the TPerson example to show only the class methods needed to serialize and deserialize using JSON using TMS WEB Core
REPLY:
Sure, here's an example of how to serialize and deserialize a TPerson
object using JSON, using only the relevant methods in the class:
unit Unit1;
interface
uses
System.JSON;
type
TPerson = class
private
FFirstName: string;
FLastName: string;
FAge: Integer;
public
property FirstName: string read FFirstName write FFirstName;
property LastName: string read FLastName write FLastName;
property Age: Integer read FAge write FAge;
function ToJSON: TJSONObject;
class function FromJSON(json: TJSONObject): TPerson;
end;
implementation
{ TPerson }
function TPerson.ToJSON: TJSONObject;
begin
Result := TJSONObject.Create;
Result.AddPair('FirstName', FFirstName);
Result.AddPair('LastName', FLastName);
Result.AddPair('Age', TJSONNumber.Create(FAge));
end;
class function TPerson.FromJSON(json: TJSONObject): TPerson;
var
person: TPerson;
begin
person := TPerson.Create;
try
person.FirstName := json.GetValue('FirstName').Value;
person.LastName := json.GetValue('LastName').Value;
person.Age := StrToInt(json.GetValue('Age').Value);
except
FreeAndNil(person);
raise;
end;
Result := person;
end;
end.
To serialize an instance of TPerson
to JSON, you can call its ToJSON
method, which returns a TJSONObject
instance representing the object's data in JSON format.
To deserialize a TPerson
instance from JSON, you can call the FromJSON
class method, passing in a TJSONObject
instance representing the object's data in JSON format. This method returns a new instance of TPerson
populated with the data from the JSON object.
Here's an example of how you could use these methods to serialize and deserialize a TPerson
instance:
var
person: TPerson;
json: TJSONObject;
jsonString: string;
begin
// Create a new person object and set its properties
person := TPerson.Create;
person.FirstName := 'John';
person.LastName := 'Doe';
person.Age := 30;
// Serialize the person object to JSON
json := person.ToJSON;
try
// Convert the JSON object to a string
jsonString := json.ToString;
// Do something with the JSON string
ShowMessage(jsonString);
finally
FreeAndNil(json);
end;
// Deserialize the person object from JSON
json := TJSONObject.ParseJSONValue(jsonString) as TJSONObject;
try
person := TPerson.FromJSON(json);
// Do something with the deserialized person object
ShowMessage(person.FirstName + ' ' + person.LastName + ', ' + IntToStr(person.Age));
finally
FreeAndNil(json);
end;
end;
=======================================
Instead of the TPerson class, you can give it your own class and it will generate the to/fromJSON methods for you.