Using fpjsontopas to generate Pascal classes from JSONΒΆ
The fpjsontopas unit allows you to generate Object Pascal class definitions from JSON data. This is useful for creating strongly-typed classes that can serialize to and from JSON format.
The basic workflow involves:
- Create a TJSONToPascal instance
- Set the JSON data using the JSON property
- Configure options like DestUnitName and ToplevelObjectClassName
- Call Execute to generate the Pascal code
- Retrieve the generated code from the Code property
Here's a simple example that generates Pascal classes from JSON data:
program JSONToPascalDemo;
{$mode objfpc}{$H+}
uses
Classes, SysUtils, fpjsontopas;
var
Generator: TJSONToPascal;
JSONData: string;
i: Integer;
begin
JSONData := '{"name": "John Doe", "age": 30, "active": true, "address": {"street": "123 Main St", "city": "Anytown"}}';
Generator := TJSONToPascal.Create(nil);
try
// Configure the generator
Generator.JSON := JSONData;
Generator.DestUnitName := 'PersonUnit';
Generator.ToplevelObjectClassName := 'TPerson';
Generator.Options := [jpoGenerateLoad, jpoGenerateSave];
// Generate the Pascal code
Generator.Execute;
// Output the generated code
Writeln('Generated Pascal unit:');
Writeln;
for i := 0 to Generator.Code.Count - 1 do
Writeln(Generator.Code[i]);
finally
Generator.Free;
end;
end.
This example will generate a complete Pascal unit with TPerson and TPersonAddress classes, including properties for each JSON field and methods to load from/save to JSON.
You can customize the generation process using various properties:
- DefaultParentName: Base class for generated objects
- FieldPrefix: Prefix for private field names
- IndentSize: Code indentation size
- ExtraUnitNames: Additional units in the uses clause
- PropertyMap: Manual type mappings for specific JSON paths