Jason Rueckert
Jason Rueckert

Reputation: 681

How to check if an item in a JsonElement exists in a seperate JsonArray?

I have a JsonElement:

JsonElement testCaseParametersJson = batchItem.getTestCase().getToolParameters().get("testCaseParameters");

of which assigns the following:

["dessert", "place", "tvShow"]

And I have a JsonArray:

JsonObject testParametersJson = batchItem.getTestParameters().getAsJsonObject();

of which assigns the following:

{"dessert": "cookies", "tvShow": "survivor", "color" : "blue"}

I'd appreciate some advice on how to check if the key in the JsonArray exists as an item in the JsonElement.

Upvotes: 0

Views: 1036

Answers (1)

Marcelo Tataje
Marcelo Tataje

Reputation: 3871

Using Gson library, you can get the String values from your JSONElement / JSONObject and do the following:

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);
    }
  }
}

Code can be summarized, and if using Java 8, you can try "forEach" loop according to your needs.

Upvotes: 1

Related Questions