2017-02-28 81 views
0

创建阵列的阵列I具有以下JSON结构:Java代码使用simpleJSon

{ 
    "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。有人可以帮助我吗? 在此先感谢。

+0

首先,我们不是一个提问和回答的网站,代码编写的服务。其次,该代码不会生成该JSON。 –

+0

我知道代码不会提供我需要的JSON。我只是想要一些建议,就像一个示例代码来构建它,这就是为什么我只是在这里发布。 Stack Over Flow一直帮助我提高技能,而且我也知道这不是一种代码编写服务。 – RRN

回答

1

您现在处于正确的轨道上,但您需要更多的代码来创建中间级别,可以无限期地以树状方式添加结构。你的示例中的顶级也是一个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"}]}]} 
+0

非常感谢Adam!这个想法解决了我的问题:) 再次感谢! – RRN