I'm on Delphi XE6 and I search the best way for create JSON and for parse JSON.
I try to work with REST.Json unit and this method : TJson.ObjectToJsonString
TContrat = class
private
FdDateDeb: TDate;
public
property dDateDeb: TDate read FdDateDeb write FdDateDeb;
end;
TApprenant = class
private
FsNom : string;
[JSONName('ListContrat')]
FListContrat: TObjectList<TContrat>;
public
property sNom : string read FsNom write FsNom;
property ListContrat: TObjectList<TContrat> read FListContrat write FListContrat;
end;
...
procedure TForm3.Button2Click(Sender: TObject);
var
apprenant : TApprenant;
contrat : TContrat;
begin
Memo1.Clear;
apprenant := TApprenant.Create;
apprenant.sNom := 'JEAN';
contrat := TContrat.Create;
contrat.dDateDeb := StrToDate('01/01/2015');
apprenant.ListContrat.Add(contrat);
contrat := TContrat.Create;
contrat.dDateDeb := StrToDate('01/01/2016');
apprenant.ListContrat.Add(contrat);
Memo1.Lines.Add(TJson.ObjectToJsonString(apprenant));
end;
the result is
{
"sNom": "JEAN",
"ListContrat": {
"ownsObjects": true,
"items": [{
"dDateDeb": 42005,
}, {
"dDateDeb": 42370,
}],
"count": 2,
"arrayManager": {}
}
}
In the result I have some property of TObjectList<> (ex "ownsObjects").
Is it the best way to create a JSON ? I must use a framework ? Have you a good tutorial ?
Sorry, I have search on forum but not found a good way.
If the JSON is just for Serializing/Deserializing (most cases) the you should deal with JSON only on the bounderies of your application.
Contracts
Define your contract(s) for the outside and use them to transport the data from inside to outside and vice versa.
First the contract unit which is designed for a convenient de-/serialization
As you can see I use arrays and classes. To manage these arrays with classes I have a base class dealing with that
Business Objects
For the application itself we use this classes only for de-/serialization. The internal business objects/entities are separated from them.
What is the benefit declare everything twice?
Well, now you can change the business objects or contracts without infecting each other. You can have different types, names in both and your internal classes are not tight bound to any contract to the outside.
See: Single Responsibility Principle
Mapping
For an easy mapping between the business objects and the contract use a mapper
Putting all together
Note This is tested on Delphi Seattle - you may have to change some of the units to get this running on XE6