JSON support in Delphi2010, a simple example

🎤 Update of this post 👉here👈

During last ITDevCon in Verona (ITALY) I talked in a session with title “Marshal and UnMarshal in Delphi 2010″ (we have published some photos about this great conference here).
In the first part of the session I’ve talked about JSON and many attendees were very interested in JSON and his application in everyday programming. I’m a real JSON fan so I decided to write this post about JSON support in Delphi2010. In my session I talked about serialization and deserialization, in this post I’ll show an example of code to do some JSON generation.

program JsonTypes;
{$APPTYPE CONSOLE}
uses
  SysUtils,
  IOUtils,
  DBXJSON;
var
  Obj, RestoredObject, JSON: TJSONObject;
  arr: TJSONArray;
begin
  json := TJSONObject.Create;
  try
    WriteLn('Empty JSON Object: ' + sLineBreak,json.ToString);
    json.AddPair('FirstName', TJSONString.Create('Daniele'));
    WriteLn('Simple JSON Object with property: ' + sLineBreak, json.ToString);
    json.AddPair(TJSONPair.Create('LastName', 'Teti'));
    WriteLn('Simple JSON Object with 2 property: ' + sLineBreak, json.ToString);
    arr := TJSONArray.Create;
    arr.Add(9871238712);
    arr.Add('peter.parker@bittime.it');
    arr.Add('Via Roma, 12');
    json.AddPair(TJSONPair.Create('Contacts', arr));
    WriteLn('JSON Object with a property array: ' + sLineBreak, json.ToString);
    obj := TJSONObject.Create;
    obj.AddPair(TJSONPair.Create('John','Doe'));
    json.AddPair('MyUndefinedPersonObject', obj);
    WriteLn('JSON Object with a nested Object: ' + sLineBreak,json.ToString);
    Write('Writing JSON object to file [jsonfile]...');
    TFile.WriteAllText('jsonfile',json.ToString);
    WriteLn('DONE!');
    RestoredObject := TJSONObject.ParseJSONValue(
      TEncoding.ASCII.GetBytes(TFile.ReadAllText('jsonfile')),0
      ) as TJSONObject;
    WriteLn('Readed JSON object from file: ' + sLineBreak, RestoredObject.ToString);
  finally
    json.Free;  //Every contained object is automatically freed
  end;
  readln; //If you want to see the output while in Delphi IDE
end.

JSON is a lightweight data-interchange format and in Delphi 2010 you have full support for it with the built-in DBXJSON unit.
Enjoy!

Comments

comments powered by Disqus