在Delphi XE5中生成带有数组的示例JSON

use*_*275 5 delphi json

来自.NET,我无法做我认为简单的任务.我想用TJSONObject,TJSONArray,TJSONPair等来构建一个简单的JSON如下所示:

{
 "APIKEY": "sadfsafsafdsa",
 "UserID": "123123123",
 "Transactions:"
        [{
           "TransactionID": 1,
           "Amount": 23
         },
         {
         "TransactionID": 2,
         "Amount": 53
         }]       
}
Run Code Online (Sandbox Code Playgroud)

按道理我会做的就是创建一个TJSONObject,然后添加3 TJSONPair,第三对是TJSONPair的交易和TJSONArrary

但是,我没有得到我想要的东西.对于Transactions对,如果我将我的事务转换TJSONArrary为字符串,那么它将作为一个无效的长字符串出现.

任何帮助,将不胜感激.

RRU*_*RUZ 13

试试这个

{$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.
Run Code Online (Sandbox Code Playgroud)

这将创建一个像这样的JSON

{   "APIKEY": "sadfsafsafdsa",   
    "UserID": "123123123",   
    "Transactions": 
    [{
      "TransactionID": "1",
      "Amount": "23"
    },
    {
      "TransactionID": "2",
      "Amount": "53"
    }] 
}
Run Code Online (Sandbox Code Playgroud)