如何使用Java代码从具有嵌套数据的Json数组中获取值

时间:2019-02-18 13:23:01

标签: java json

我必须从具有嵌套数据的数组“ machines”中获取值,并且需要获取“ value1”:“需要获取此值”。尝试了很多代码,但仍然无法获取相同的代码。

{
   "name":"anyname",
   "machines":[
      {
         "id":"771760",
         "type":"general",
         "properties":{
            "value1":"1",
            "value2":"2"
         }
      },
      {
         "id":"341256",
         "type":"general",
         "properties":{
            "value1":"Need to fetch this value"
         }
      },
      {
         "id":"341256",
         "type":"general",
         "properties":{
            "value1":"1",
            "value2":"2"
         }
      }
   ]
}

尝试使用JsonObject和JsonArray,仍然无法正常工作

public String getValueForAnyKeyHavingNestedObjects(String jsonData,String outerObjectKey, String keyWhoseValueToFetch) throws JSONException {

JSONObject obj = new JSONObject(jsonData);

String value = String.valueOf(obj.getJSONObject(outerObjectKey).get(keyWhoseValueToFetch));
return value;
}

1 个答案:

答案 0 :(得分:2)

因此,您拥有需要放入JSONObject中的jsonData。

您需要提取计算机,该计算机是使用getJSONArray("machines")的数组。

之后,您要遍历每个machine并将machine转换为另一个JSONObject

要获取value1,您只需执行普通的get("value1")

完整示例在这里:

public static void main(String[] args) {
        String jsonData = "{\n"
                + "   \"name\":\"anyname\",\n"
                + "   \"machines\":[\n"
                + "      {\n"
                + "         \"id\":\"771760\",\n"
                + "         \"type\":\"general\",\n"
                + "         \"properties\":{\n"
                + "            \"value1\":\"1\",\n"
                + "            \"value2\":\"2\"\n"
                + "         }\n"
                + "      },\n"
                + "      {\n"
                + "         \"id\":\"341256\",\n"
                + "         \"type\":\"general\",\n"
                + "         \"properties\":{\n"
                + "            \"value1\":\"Need to fetch this value\"\n"
                + "         }\n"
                + "      },\n"
                + "      {\n"
                + "         \"id\":\"341256\",\n"
                + "         \"type\":\"general\",\n"
                + "         \"properties\":{\n"
                + "            \"value1\":\"1\",\n"
                + "            \"value2\":\"2\"\n"
                + "         }\n"
                + "      }\n"
                + "   ]\n"
                + "}";

        final JSONObject jsonObject = new JSONObject(jsonData);
        final JSONArray machines = jsonObject.getJSONArray("machines");
        for (int i = 0; i < machines.length(); i++) {
            final JSONObject machine = machines.getJSONObject(i);
            final JSONObject properties = machine.getJSONObject("properties");
            System.out.println(properties.get("value1"));
        }
    }

结果:

  

1

     

需要获取此值

     

1