来自.NET,我无法做我认为简单的任务。
我想使用TJSONObject
,TJSONArray
,TJSONPair
等来构建一个简单的JSON,如下所示:
{
"APIKEY": "sadfsafsafdsa",
"UserID": "123123123",
"Transactions:"
[{
"TransactionID": 1,
"Amount": 23
},
{
"TransactionID": 2,
"Amount": 53
}]
}
逻辑上,我要做的是创建TJSONObject
,然后添加3 TJSONPair
,第三对是交易的TJSONPair
和{{1} }
然而,我没有得到我想要的东西。对于 Transactions 对,如果我将我的事务TJSONArrary
转换为字符串,那么它将作为一个无效的长字符串出现。
任何帮助将不胜感激。
答案 0 :(得分:12)
试试这个
{$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
{ "APIKEY": "sadfsafsafdsa",
"UserID": "123123123",
"Transactions":
[{
"TransactionID": "1",
"Amount": "23"
},
{
"TransactionID": "2",
"Amount": "53"
}]
}