To convert JSON to a class in Delphi, you can use the TJSON.Parse method provided by the REST.Json unit. This method takes a string representation of a JSON object or array and converts it to a Delphi object or array.
Here is an example of how to use TJSON.Parse to convert a JSON object to a Delphi class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
uses REST.Json; type TPerson = class private FName: string; FAge: Integer; public property Name: string read FName write FName; property Age: Integer read FAge write FAge; end; var JSONString: string; Person: TPerson; begin JSONString := ‘{“name”:”John”,”age”:30}’; Person := TJSON.Parse<TPerson>(JSONString); WriteLn(Person.Name); // outputs “John” WriteLn(Person.Age); // outputs 30 end. |
Here is an example of how to use TJSON.Parse to convert a JSON array to a Delphi dynamic array:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
uses REST.Json; type TPerson = class private FName: string; FAge: Integer; public property Name: string read FName write FName; property Age: Integer read FAge write FAge; end; var JSONString: string; People: TArray<TPerson>; Person: TPerson; begin JSONString := ‘[{“name”:”John”,”age”:30},{“name”:”Jane”,”age”:25}]’; People := TJSON.Parse<TArray<TPerson>>(JSONString); for Person in People do begin WriteLn(Person.Name); WriteLn(Person.Age); end; // Output: // John // 30 // Jane // 25 end. |
Note that the TPerson class in the above examples must have properties that match the names and types of the JSON object properties. The REST.Json unit uses these property names and types to map the JSON data to the Delphi object.
You can also use the TJSON.ToJson method provided by the REST.Json unit to convert a Delphi object or array to a JSON string. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
uses REST.Json; type TPerson = class private FName: string; FAge: Integer; public property Name: string read FName write FName; property Age: Integer read FAge write FAge; end; var Person: TPerson; JSONString: string; begin Person := TPerson.Create; Person.Name := ‘John’; Person.Age := 30; JSONString := TJSON.ToJson(Person); WriteLn(JSONString); // outputs ‘{“name”:”John”,”age”:30}’ end. |
Leave a Reply