REST.JSON での直列化
JSON の色々を調査中で、その一環として見つかったので書きます。
こんな書き方すると各方面の方に怒られますが、手続き的に。
procedure TForm1.JSON; var PersonList: TList<TPerson>; JsonObj: TJSONObject; begin PersonList := nil; JsonObj := nil; try PersonList := TObjectList<TPerson>.Create(); PersonList.Add(TPerson.Create()); PersonList.Last.Name := 'Alice'; PersonList.Last.EMail := 'Alice@wonderland.org'; PersonList.Add(TPerson.Create()); PersonList.Last.Name := 'Bob'; PersonList.Last.EMail := 'Bob@wonderland.org'; JsonObj := TJSON.ObjectToJsonObject(PersonList); Memo1.Lines.Clear(); Memo1.Lines.Add(JsonObj.GetValue('items').ToString) finally FreeAndNil(JsonObj); FreeAndNil(PersonList); end; end;
で、実行したやつを整形した奴が、以下になります。
[ { "eMail": "Alice@wonderland.org", "name": "Alice" }, { "eMail": "Bob@wonderland.org", "name": "Bob" } ]
Memo1.Lines.Add(JsonObj.GetValue('items').ToString)
としているのは、データ以外の物もくっついてくるから。
Memo1.Lines.Add(JsonObj.ToString)
にすると、以下の通り。
{ "items": [ { "eMail": "Alice@wonderland.org", "name": "Alice" }, { "eMail": "Bob@wonderland.org", "name": "Bob" } ], "listHelper": [ 2 ], "ownsObjects": true }
総合すると、使えないことないけどやりやすいかと言われると微妙、という所。
Delphi のアプリケーションだけでやりとりするならともかく、他言語が絡んでくると items 以外は邪魔だし・・・
まぁ、REST.* のパッケージ多めなので、その辺含めて要確認ですな。