Java JSON / GSON - 搜索数组中的所有对象并返回匹配

时间:2017-01-13 10:58:37

标签: java json gson

我正在返回一个包含许多对象的JSON数组,我希望能够搜索每个对象中的属性,然后返回符合此条件的对象。

我能够返回JSON数组但是我在如何搜索对象以使属性值与给定值匹配时遇到了麻烦。

数组中的一些示例值:

[
  {"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384640123117E9,"uID":"136199_3_10"},
  {"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483379834470379E9,"uID":"136199_3_10"},
  {"blobJson":"x","deviceMfg":10,"eventCode":0,"sensorClass":3,"sensorUUID":"136199","timeStamp":1.483384639621985E9,"uID":"136199_3_10"}
]

我正在使用以下代码返回数组,该数组按预期工作:

   JsonParser jp = new JsonParser(); 
   JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); 
   JsonArray rootArr = root.getAsJsonArray();

以下代码块是我用于在对象中搜索给定属性值的代码,此代码仅在返回对象时起作用,但在返回整个数组时出错:

   JsonObject rootObj = rootArr.getAsJsonObject();
   for (String attribute : attributes) {
     System.out.println(rootObj.get(attribute).getAsString());
   }

它给出了错误:

java.lang.IllegalStateException: Not a JSON Object:

我尝试将rootObj.get(attribute)更改为rootArr.get(attribute),但会返回错误:

incompatible types: java.lang.String cannot be converted to int

这是方法调用:

method("136199", Arrays.asList("blobJson", "deviceMfg", "uID"));

方法声明:

 void method(String sensor, List<String> attributes)

2 个答案:

答案 0 :(得分:1)

问题是您正在尝试将JsonArray视为JsonObject。尝试以下代码,看看它是否适合您。现在感兴趣的是 - JsonObject rootObj = rootArr.get(0).getAsJsonObject();

public static void main(String[] args) {

    String json = "[{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384640123117E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483379834470379E9,\"uID\":\"136199_3_10\"},{\"blobJson\":\"x\",\"deviceMfg\":10,\"eventCode\":0,\"sensorClass\":3,\"sensorUUID\":\"136199\",\"timeStamp\":1.483384639621985E9,\"uID\":\"136199_3_10\"}]";

    JsonParser jp = new JsonParser();
    JsonElement root = jp.parse(json);
    JsonArray rootArr = root.getAsJsonArray();

    JsonObject rootObj = rootArr.get(0).getAsJsonObject();
    rootObj.entrySet().forEach(entry -> System.out.println(entry.getKey()+": "+entry.getValue().getAsString()));

}

答案 1 :(得分:0)

以下是您可以尝试的内容

 try {
    JSONArray jsonArray = new JSONArray(data);
    for (int i = 0; i < jsonArray.length(); i++) {
    Log.e("JSON Count", jsonArray.get(i).toString());
   }
} catch (Exception e) {
}