You can now serialize TObjectList instances, after a proper call to TJSONSerializer.RegisterClassForJSON() method.

In fact, if ObjectToJSON() or TJSONWriter.WriteObject() have their woStoreClassName option defined, a new "ClassName": field will be written as first field of the serialized JSON object.

This new "ClassName" field will be recognized:

  • by JSONToObject() for TObjectList members, 
  • and by the new JSONToNewObject() method.

Note that all TSQLRecord classes of a model are automatically registered via a call to TJSONSerializer.RegisterClassForJSON(): you do not have to register them, and can directly serialize TObjectList of TSQLRecords.

As a consequence, this kind of code can now work:

// register the type (but Classes.RegisterClass list is also checked)
// create an instance by reading the textual class name field
J := '{"ClassName":"TComplexNumber", "Real": 10.3, "Imaginary": 7.92 }';
P := @J[1]; // make local copy of constant
Comp := TComplexNumber(JSONToNewObject(P,Valid));
// here Comp is a valid unserialized object :)
// do not forget to free the memory (Comp can be nill if JSON was not valid)

Internal TObjectList process will therefore rely on a similar process, creating the proper class instances on the fly. You can even have several classes appearing in one TObjectList: the only prerequisite is that all class types shall have been previously registered on both sides, by a call to TJSONSerializer.RegisterClassForJSON().

Feedback is welcome on our forum.