Skip to content

Instantly share code, notes, and snippets.

@danieleteti
Created August 18, 2023 08:27
Show Gist options
  • Save danieleteti/746fcb99780f4bbf72d8aefc6038cb61 to your computer and use it in GitHub Desktop.
Save danieleteti/746fcb99780f4bbf72d8aefc6038cb61 to your computer and use it in GitHub Desktop.
Sample JSON support in Delphi
program JSONSupportDemo;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.IOUtils,
  System.JSON;

var
  lJSON, lJNestedObject, lJRestoredObject: TJSONObject;
  lJContacts: TJSONArray;
  lOutValue: TJSONString;
  lOutContacts: TJSONArray;

procedure Separator;
begin
  WriteLn(sLineBreak + StringOfChar('-', 40) + sLineBreak);
end;

begin
  lJSON := TJSONObject.Create;
  try
    WriteLn('Empty JSON Object: ' + sLineBreak, lJSON.Format());
    Separator;
    // let's add some json properties
    lJSON.AddPair('firstName', TJSONString.Create('Daniele'));
    WriteLn('Simple JSON Object with a single property: ' + sLineBreak, lJSON.Format());
    Separator;

    lJSON.AddPair(TJSONPair.Create('lastName', 'Teti'));
    WriteLn('Simple JSON Object with 2 property: ' + sLineBreak, lJSON.Format());
    Separator;

    // create an array property to store contacts
    lJContacts := TJSONArray.Create;
    lJSON.AddPair(TJSONPair.Create('contacts', lJContacts));
    lJContacts.Add(555789456);
    lJContacts.Add('peter.parker@bittime.it');
    lJContacts.Add('Via Roma, 12');
    WriteLn('JSON Object with a property array: ' + sLineBreak, lJSON.Format());
    Separator;

    // let's nest a JSON object as property of the main JSON object
    lJNestedObject := TJSONObject.Create;
    lJSON.AddPair('bestFriend', lJNestedObject);
    lJNestedObject.AddPair(TJSONPair.Create('firstName', 'John'));
    lJNestedObject.AddPair(TJSONPair.Create('lastName', 'Doe'));
    WriteLn('JSON Object with a nested Object: ' + sLineBreak, lJSON.Format());
    Separator;

    Write('Writing JSON object to file [jsonfile]...');
    TFile.WriteAllText('jsonfile', lJSON.Format());
    WriteLn('DONE!');

    Separator;

    lJRestoredObject := TJSONObject.ParseJSONValue(TFile.ReadAllText('jsonfile')) as TJSONObject;
    try
      WriteLn('Read JSON object from file: ' + sLineBreak, lJRestoredObject.Format());

      Separator;
      WriteLn('Navigate JSON object properties: ');
      { some different ways to read object properties}
      //1
      WriteLn('firstName -> ' + lJRestoredObject.GetValue<TJSONString>('firstName').Value);
      //2
      WriteLn('firstName -> ' + lJRestoredObject.Values['firstName'].Value);
      //3
      WriteLn('lastName  -> ' + lJRestoredObject.P['lastName'].Value);
      //4
      if lJRestoredObject.TryGetValue<TJSONString>('lastName', lOutValue) then
      begin
        WriteLn('lastName  -> ' + lOutValue.Value);
      end;

      //How to read an array
      Separator;
      //1 way - fails if "contacts" is not an array
      WriteLn('There are ' + (lJRestoredObject.Values['contacts'] as TJSONArray).Count.ToString + ' contacts');
      for var I := 0 to TJSONArray(lJRestoredObject.Values['contacts']).Count - 1 do
      begin
        WriteLn('  contacts[' + I.ToString + ']  -> ' + lJRestoredObject.Values['contacts'].A[I].Value);
      end;

      Separator;
      //2 way - safe because "if" driven
      if lJRestoredObject.TryGetValue<TJSONArray>('contacts', lOutContacts) then
      begin
        WriteLn('There are ' + lOutContacts.Count.ToString + ' contacts');
        for var I := 0 to lOutContacts.Count - 1 do
        begin
          WriteLn('  contacts[' + I.ToString + ']  -> ' + lOutContacts[I].Value);
        end;
      end;

      Separator;
      //Reading a nested property using Path
      Writeln('Reading a nested property using Path');
      Writeln('BestFriend''s name -> ' + lJRestoredObject.P['bestFriend.firstName'].Value);

    finally
      lJRestoredObject.Free;
    end;
  finally
    lJSON.Free; // Every contained object is automatically freed when parent is freed
  end;

  if DebugHook <> 0 then
  begin
    Separator;
    Write('Press return to exit...');
    ReadLn; // If you want to see the output while in Delphi IDE
  end;

end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment