coming from .NET, I've been unable to do what I consider a simple task.
I want to use TJSONObject
, TJSONArray
, TJSONPair
etc to construct a simple JSON like the following:
{
"APIKEY": "sadfsafsafdsa",
"UserID": "123123123",
"Transactions:"
[{
"TransactionID": 1,
"Amount": 23
},
{
"TransactionID": 2,
"Amount": 53
}]
}
Logically what I would do is create a TJSONObject
and then add 3 TJSONPair
, the third pair being TJSONPair
of Transactions and a TJSONArrary
However, I am not getting what I wanted. For the Transactions pair, if I convert my transactions TJSONArrary
to string, then it comes out as a long string which is invalid.
Any help would be appreciated.
Try this
{$APPTYPE CONSOLE}
{$R *.res}
uses
Data.DBXJSON,
System.SysUtils;
var
LJson, LJsonObject: TJSONObject;
LArr: TJSONArray;
begin
try
ReportMemoryLeaksOnShutdown:=True;
LJsonObject := TJSONObject.Create;
try
LJsonObject.AddPair(TJSONPair.Create('APIKEY', 'sadfsafsafdsa'));
LJsonObject.AddPair(TJSONPair.Create('UserID', '123123123'));
LArr := TJSONArray.Create;
LJson := TJSONObject.Create;
LJson.AddPair(TJSONPair.Create('TransactionID', '1'));
LJson.AddPair(TJSONPair.Create('Amount', '23'));
LArr.Add(LJson);
LJson := TJSONObject.Create;
LJson.AddPair(TJSONPair.Create('TransactionID', '2'));
LJson.AddPair(TJSONPair.Create('Amount', '53'));
LArr.Add(LJson);
LJsonObject.AddPair(TJSONPair.Create('Transactions', LArr));
Write(LJsonObject.ToString);
finally
LJsonObject.Free; //free all the child objects.
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Readln;
end.
This will create a JSON like so
{ "APIKEY": "sadfsafsafdsa",
"UserID": "123123123",
"Transactions":
[{
"TransactionID": "1",
"Amount": "23"
},
{
"TransactionID": "2",
"Amount": "53"
}]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With