我使用org.json
来查找json对象和值(需要org.json
),并且我试图访问子数组元素。在Java中获取JSON嵌套数组元素
我的JSON:
{
"Info": {
"name": "my_json",
},
"my_array": {
"arrays": [
{
"array 1": [
{
"name": "red",
"server": "red1",
"capacity": "123"
},
{
"name": "blue",
"server": "blue1",
"capacity": "456"
}
]
},
{
"array 2": [
{
"name": "white",
"server": "white1",
"capacity": "1234"
},
{
"name": "black",
"server": "black1",
"capacity": "4567"
}
]
}
]
}
}
此输出:
{"array 1":[
{"name":"red","capacity":"123","server":"red1"},
{"capacity":"456","name":"blue","name":"blue1"}
]}
{"array 2":[
{"capacacity":"1234","name":"white","server":"white1"},
{"name":"black","capacity":"4567","server":"black1"}
]}
{"array 1":[
{"name":"red","capacity":"123","server":"red1"},
{"capacity":"456","name":"blue","name":"blue1"}
]}
{"array 2":[
{"capacity":"1234","name":"white","server":"white1"},
{"name":"black","capacity":"4567","server":"black1"}
]}
的方法是这样的:
public static String processJson(String[] args) throws JSONException {
String value = "";
String jsonData = readFile(args[0]);
JSONObject jobj = new JSONObject(jsonData);
if (args[1].equals("my_array")) {
JSONObject parent = jobj.getJSONObject("my_array");
JSONArray jarr = parent.getJSONArray("arrays");
for (int i = 0; i < jarr.length(); i++) {
for (int j = 0; j < jarr.length(); j++) {
JSONObject test1 = jarr.getJSONObject(j);
System.out.println(test1);
}
}
}
return value;
}
我想返回值是:
[{"name":"red","capacity":"123","server":"red1"
{"capacity":"456","name":"blue","name":"blue1"}]
是否有可能获得array 1
元素? 我认为嵌套循环会照顾它,但它只输出同一时间。
什么是ARGS [1]? – jeanr
@jeanr我想这是'my_array' –
当我尝试读取json有效载荷的结构时,它看起来像这样:my_array.arrays [0]。“array 1” my_array.arrays [1]。“array 1” 你确定你的json格式排列整齐,即在一个适当的层次或关系? – dirai