[英]Java code to create an array of array using simpleJSon
I have the following JSON structure: 我具有以下JSON结构:
{
"PARAMORDER": [{
"TAB1": [{
"1": "Picture ID Source"
}, {
"2": "Place of Issuance"
}],
"TAB2": [{
"1": "Picture ID Source"
}, {
"2": "Place of Issuance"
}]
}]
}
I am trying to create a JSON Array using java code which looks like the above format when it is parsed and retrieved. 我正在尝试使用Java代码创建一个JSON数组,当解析和检索它时,它看起来像上面的格式。 I am using org.json.simple API for this. 我为此使用org.json.simple API。 However I am unable to create an array of array in JSON using java code. 但是我无法使用Java代码在JSON中创建数组的数组。 Can someone please share me a sample code which can construct the JSON in the above format. 有人可以分享给我一个示例代码,它可以用上述格式构造JSON。
Below is the sample code I tried which creates a json array: 以下是我尝试创建json数组的示例代码:
JSONArray jsonArray = new JSONArray();
JSONObject firstJson = new JSONObject();
JSONObject secondJson = new JSONObject();
firstJson.put("1", "Picture ID Source");
secondJson.put("1", "Picture ID Source");
jsonArray.add(firstJson);
jsonArray.add(secondJson);
System.out.println(jsonArray.toString);
This gives me the following JSON: 这给了我以下JSON:
[{
"1": "Picture ID Source"
}, {
"1": "Picturesecond ID Source"
}]
I am unable to create a JSONArray of JSONArray. 我无法创建JSONArray的JSONArray。 Can someone please help me with that? 有人可以帮我吗? Thanks in Advance. 提前致谢。
You're on the right track, but you need a lot more code to create the intermediate levels, the structures can be added in a tree-like manner indefinitely. 您处在正确的轨道上,但是需要更多的代码来创建中间级别,可以无限期地以树状方式添加结构。 Also your top level in your sample is a JSON object, not an array. 此外,样本中的最高层是JSON对象,而不是数组。
JSONObject root = new JSONObject();
JSONArray paraArray = new JSONArray();
JSONObject a = new JSONObject();
JSONArray tab1 = new JSONArray();
JSONObject source1 = new JSONObject();
source1.put("1", "Picture ID Source");
tab1.add(source1);
JSONObject source2 = new JSONObject();
source2.put("2", "Place of Issuance");
tab1.add(source2);
a.put("TAB1", tab1);
paraArray.add(a);
JSONObject b = new JSONObject();
JSONArray tab2 = new JSONArray();
JSONObject source3 = new JSONObject();
source3.put("1", "Picture ID Source");
tab2.add(source3);
JSONObject source4 = new JSONObject();
source4.put("2", "Place of Issuance");
tab2.add(source4);
b.put("TAB2", tab2);
paraArray.add(b);
root.put("PARAMORDER", paraArray);
System.out.println(root.toString());
Output 输出量
{"PARAMORDER":[{"TAB1":[{"1":"Picture ID Source"},{"2":"Place of Issuance"}]},{"TAB2":[{"1":"Picture ID Source"},{"2":"Place of Issuance"}]}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.