| [Up] |
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:
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; or := 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: