我有一个 JsonElement:
JsonElement testCaseParametersJson = batchItem.getTestCase().getToolParameters().get("testCaseParameters");
其中分配以下内容:
["dessert", "place", "tvShow"]
我有一个 JsonArray:
JsonObject testParametersJson = batchItem.getTestParameters().getAsJsonObject();
其中分配以下内容:
{"dessert": "cookies", "tvShow": "survivor", "color" : "blue"}
我希望获得一些有关如何检查 JsonArray 中的键是否作为 JsonElement 中的项目存在的建议。
最佳答案
使用 Gson 库,您可以从 JSONElement/JSONObject 获取字符串值并执行以下操作:
String jsonObject = "{\"dessert\": \"cookies\", \"tvShow\": \"survivor\", \"color\" : \"blue\"}";
String jsonArray = "[\"dessert\", \"place\", \"tvShow\"]";
Map<String, String> objMap = new Gson().fromJson(jsonObject, new TypeToken<HashMap<String, String>>() {}.getType());
List<String> arrayVals = new Gson().fromJson(jsonArray, new TypeToken<List<String>>(){}.getType());
for(Entry<String, String> entry : objMap.entrySet()) {
for (String val : arrayVals) {
if (entry.getKey().equals(val)) {
System.out.println("Found value in key set: " + val);
}
}
}
代码可以总结,如果使用Java 8,可以根据需要尝试“forEach”循环。
关于java - 如何检查 JsonElement 中的项目是否存在于单独的 JsonArray 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46609333/