Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a sample JSON with an array in it in Delphi XE5

Tags:

json

delphi

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.

like image 876
user1552275 Avatar asked Jan 15 '14 23:01

user1552275


1 Answers

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"
    }] 
}
like image 176
RRUZ Avatar answered Sep 27 '22 00:09

RRUZ