在Java中获取JSON嵌套数组元素

时间:2017-08-02 07:21:41

标签: java arrays json org.json

我正在使用org.json来查找json对象和值(org.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元素? 我认为嵌套循环会处理它,但它只输出相同的时间。

1 个答案:

答案 0 :(得分:2)

如果您只想要第一个元素,那么您不需要循环

       JSONObject test1 = jarr.getJSONObject(0);
       System.out.println(test1);

如果您想格式化test1您的

System.out.println (test1.toString ().replace ("{\"array 1\":", ""));