[Up] Reference for unit 'fpJsonToPas' (#fcl)

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:

  1. Create a TJSONToPascal instance
  2. Set the JSON data using the JSON property
  3. Configure options like DestUnitName and ToplevelObjectClassName
  4. Call Execute to generate the Pascal code
  5. 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;
    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:


Documentation generated on: Jan 27 2026