Delphi:JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10549935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Delphi: JSON array
提问by dedoki
Trying to understand the JSON in Delphi. Using the module "DBXJSON.pas". How to use it to make this such an array:
试图理解 Delphi 中的 JSON。使用模块“DBXJSON.pas”。如何使用它来制作这样的数组:
Array:[
{"1":1_1,"1_2_1":1_2_2},
...,
]
Doing so:
这样做:
JSONObject:=TJSONObject.Create;
JSONArray:=TJSONArray.Create();
...
JSONArray.AddElement(TJSONObject.Create(TJSONPair.Create('1','1_1')));
JSONArray.AddElement(TJSONObject.Create(TJSONPair.Create('1_2_1','1_2_2')));
JSONObject.AddPair('Array',JSONArray);
, but get this:
,但得到这个:
{
"Array":[
{"1":"1_1"},{"1_2_1":"1_2_2"}
]
}
Please help! Thanks!
请帮忙!谢谢!
回答by teran
Code, wich you posted above, is not correct. You've created an JSON-Array and trying to add pair-elements to that array. But, instead of adding pairs to array you have to add JSON Objectsto this array, and these objects have to contain your pairs.
here is an sample code to solve your problem:
您在上面发布的代码不正确。您已经创建了一个 JSON-Array 并尝试向该数组添加对元素。但是,不是将对添加到数组中,您必须添加JSON Objects到该数组中,并且这些对象必须包含您的对。
这是解决您的问题的示例代码:
program Project3;
{$APPTYPE CONSOLE}
uses
SysUtils, dbxjson;
var jsobj, jso : TJsonObject;
jsa : TJsonArray;
jsp : TJsonPair;
begin
try
//create top-level object
jsObj := TJsonObject.Create();
//create an json-array
jsa := TJsonArray.Create();
//add array to object
jsp := TJSONPair.Create('Array', jsa);
jsObj.AddPair(jsp);
//add items to the _first_ elemet of array
jso := TJsonObject.Create();
//add object pairs
jso.AddPair(TJsonPair.Create('1', '1_1'));
jso.AddPair(TJsonPair.Create('1_2_1', '1_2_2'));
//put it into array
jsa.AddElement(jso);
//second element
jso := TJsonObject.Create();
//add object pairs
jso.AddPair(TJsonPair.Create('x', 'x_x'));
jso.AddPair(TJsonPair.Create('x_y_x', 'x_y_y'));
//put it into array
jsa.AddElement(jso);
writeln(jsObj.ToString);
readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
and output is
和输出是
{"Array":[
{"1":"1_1","1_2_1":"1_2_2"},
{"x":"x_x","x_y_x":"x_y_y"}
]
}
回答by umlcat
Same answer as @teran:
与@teran 相同的答案:
change:
改变:
JSONArray.AddElement(TJSONObject.Create(TJSONPair.Create('1','1_1')));
JSONArray.AddElement(TJSONObject.Create(TJSONPair.Create('1_2_1','1_2_2')));
to:
到:
JSONArray.AddElement(TJSONPair.Create('1','1_1'));
JSONArray.AddElement(TJSONPair.Create('1_2_1','1_2_2'));
Cheers.
干杯。

