-
Notifications
You must be signed in to change notification settings - Fork 182
Serialization
Koltcov edited this page May 13, 2015
·
5 revisions
Serialization currently only works on public fields. However, the long-term plan is to use properties too and give configuration options. Field names are case sensitive. Take the following class as an example:
TPerson = class(TObject)
public
(* Field names match the JSON field names, including case *)
id: Integer;
[JsonName('personeName')] // it is optional
name: String;
email: String;
(* Static constructor *)
class function NewFrom(Id: Integer; Name, EMail: String): TPerson;
end;
Would map to the following JSON:
{
"id": 12345,
"personeName": "David Example",
"email": "[email protected]"
}
Now serialization is available for delphi 2009 and older, using old RTTI(Run-time Type Information). This serialization mode is much more restricted, due to own limitations of existing RTTI in previous versions of Delphi.
There are some prerequisites for the class definition:
- Are only accepted properties
- The properties must be defined in the published section
- The class should enable compiler directives to include type information at run-time.This can be done inheriting of TPersistent class, or declaring the class manually between compiler directives
{$M }
and{$M-}.
See the example below:
-
Inheriting TPersistent
TPerson = class(TPersistent) private //omitted fields published property id: Integer read FId write FId; property name: String read FName write FName; property email: String read FEmail write FEmail; end;
-
Using compiler directives(no need to use inheritance)
{$M } or {$TYPEINFO ON} TPerson = class private //omitted fields published property id: Integer read FId write FId; property name: String read FName write FName; property email: String read FEmail write FEmail; end; {$M-} or {$TYPEINFO OFF}