Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I populate a JSON array with values (not pairs) in Delphi?

I'm trying to create JSON that looks like this:

{ "guestlist": ["alice","bob","charlie"] }

Typical examples I see for populating a JSON array look like this:

var 
  jsobj: TJsonObject;      
  jso : TJsonObject;      
  jsa : TJsonArray;
  jsp : TJsonPair;

begin
    jsObj := TJsonObject.Create();
    jsa := TJsonArray.Create();
    jsp := TJSONPair.Create('guestlist', jsa);
    jsObj.AddPair(jsp);

    jso := TJsonObject.Create();
    jso.AddPair(TJSONPair.Create('person', 'alice'));
    jsa.AddElement(jso);

    jso := TJsonObject.Create();
    jso.AddPair(TJSONPair.Create('person', 'bob'));
    jsa.AddElement(jso);

    jso := TJsonObject.Create();
    jso.AddPair(TJSONPair.Create('person', 'charlie'));
    jsa.AddElement(jso);
end;

But that would result in something like this:

{ "guestlist": [{"person":"alice"},{"person":"bob"},{"person":"charlie"}] }

How can I add a single value to the array instead of a pair? I see nothing in the documentation for TJsonObject on how to do this,

like image 453
BIBD Avatar asked Dec 11 '22 18:12

BIBD


1 Answers

This is actually a lot simpler than you're making it out to be. A TJSONArray can happily contain any TJSONValue as elements so the solution is really quite straightforward.

program Project1;
{$APPTYPE CONSOLE}

uses
  JSON;

var
  LJObj : TJSONObject;
  LGuestList : TJSONArray;
begin

  LGuestlist := TJSONArray.Create();
  LGuestList.Add('alice');
  LGuestList.Add('bob');
  LGuestList.Add('charlie');

  LJObj := TJSONObject.Create;
  LJObj.AddPair(TJSONPair.Create('guestlist', LGuestList));

  WriteLn(LJObj.ToString);
  ReadLn;
end.

Produces output :

{"guestlist":["alice","bob","charlie"]}
like image 156
J... Avatar answered Dec 13 '22 07:12

J...