在Delphi XE5中生成带有数组的示例JSON [英] Generate a sample JSON with an array in it in Delphi XE5

查看:811
本文介绍了在Delphi XE5中生成带有数组的示例JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自.NET,我一直无法完成我认为简单的任务. 我想使用TJSONObjectTJSONArrayTJSONPair等来构造一个简单的JSON,如下所示:

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
         }]       
}

从逻辑上讲,我要做的是创建一个TJSONObject,然后添加3个TJSONPair,第三对是 Transactions TJSONPair和一个TJSONArrary

Logically what I would do is create a TJSONObject and then add 3 TJSONPair, the third pair being TJSONPair of Transactions and a TJSONArrary

但是,我没有得到想要的东西.对于交易对,如果我将交易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.

推荐答案

尝试一下

{$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.

这将创建一个像这样的JSON

This will create a JSON like so

{   "APIKEY": "sadfsafsafdsa",   
    "UserID": "123123123",   
    "Transactions": 
    [{
      "TransactionID": "1",
      "Amount": "23"
    },
    {
      "TransactionID": "2",
      "Amount": "53"
    }] 
}

这篇关于在Delphi XE5中生成带有数组的示例JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆