Reputation: 15414
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,
Upvotes: 4
Views: 2682
Reputation: 36850
Just in case you'd be interested in looking at an alternative: I created jsonDoc, primarily because I like COM interfaces and OleVariants, and dislike long lists of overloads. Then the above code could like like this:
JSON(['guestlist',
VarArrayOf([JSON(['person','alice']),
JSON(['person','bob']),
JSON(['person','charlie'])
])
])
Upvotes: 4
Reputation: 31453
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"]}
Upvotes: 9