Skip to content

NeonAutoCreate

Paolo Rossi edited this page May 5, 2024 · 1 revision

NeonAutoCreate attribute

The NeonAutoCreate attribute is useful (in deserialization) when you have a sub-object in a class that it’s not always created but instead it’s creation must be controlled by the JSON data.

If Neon encounters the NeonAutoCreate attribute, then tries to create the sub-object but only if the sub-object reference is nil (to avoid memory leaks)

Here’s an example:

  TAutoClass = class
  private
    FID: Integer;
  public
    property ID: Integer read FID write FID;
  end;

  TParentClass = class
  private
    FName: string;
    FAuto: TAutoClass;
  public
    constructor Create;
    destructor Destroy; override;

    property Name: string read FName write FName;
    [NeonAutoCreate]
    property Auto: TAutoClass read FAuto write FAuto;
  end;

If we have a JSON object like the one in the next example, Neon will create for you the Auto object:

{
  "Name": "Paolo",
  "Auto": {
    "ID": 2233
  }
}

In Neon if you want to create every nil sub-objects automatically you can use the config setting SetAutoCreate(True) to enable automatic creation of objects globally for every object Neon encounters.

NeonAutoCreate vs NeonFactory

In Neon there is also the NeonFactory attribute that adds the capability of creating object depending on the JSON values. So what is the difference between the two?

NeonAutoCreate is the easiest way to create a sub-object but you can’t control how this object is created (the sub-object must have a parameterless constructor that Neon will call upon creation) with NeonFactory you can provide the actual code that creates the sub-object, so you can pass parameters, verify conditions and so on…

Remarks

The sub-object must be nil

The destruction of the Auto object is (always) responsibility of the TParentClass

The sub-object must have a default constructor (parameterless Create)

Clone this wiki locally