使用simpleJSon创建数组的Java代码
我有以下JSON结构:使用simpleJSon创建数组的Java代码,java,json,simplejson,Java,Json,Simplejson,我有以下JSON结构: { "PARAMORDER": [{ "TAB1": [{ "1": "Picture ID Source" }, { "2": "Place of Issuance" }], "TAB2": [{ "1": "Picture ID Source" }, { "2": "Place of
{
"PARAMORDER": [{
"TAB1": [{
"1": "Picture ID Source"
}, {
"2": "Place of Issuance"
}],
"TAB2": [{
"1": "Picture ID Source"
}, {
"2": "Place of Issuance"
}]
}]
}
我正在尝试使用java代码创建一个JSON数组,在解析和检索该数组时,它与上面的格式类似。我正在为此使用org.json.simple API。但是,我无法使用java代码在JSON中创建数组数组。有人能给我分享一个示例代码,可以用上面的格式构造JSON
下面是我尝试的创建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);
这为我提供了以下JSON:
[{
"1": "Picture ID Source"
}, {
"1": "Picturesecond ID Source"
}]
我无法创建JSONArray的JSONArray。有人能帮我吗?
提前感谢。您的思路是正确的,但是您需要更多的代码来创建中间层,结构可以无限期地以树状方式添加。此外,示例中的顶层是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());
输出
{"PARAMORDER":[{"TAB1":[{"1":"Picture ID Source"},{"2":"Place of Issuance"}]},{"TAB2":[{"1":"Picture ID Source"},{"2":"Place of Issuance"}]}]}
首先,我们不是一个问答网站,代码编写服务。其次,该代码不会生成JSON,我知道该代码不会提供我需要的JSON。我只是想得到一些建议,比如一个构建它的示例代码,这就是我为什么在这里发表文章的原因。堆栈溢出一直帮助我提高我的技能,我也知道这不是一个代码编写服务。非常感谢Adam!!这个想法解决了我的问题:再次感谢!!