javaarraysjsongsonjson-simple

How to check if a value exists in a JSON Array for a particular key?


My JSON array file:

[
    {
      "setName": "set-1",
      "testTagName": "Test1",
      "methodName": "addCustomer"
    },
    {
        "setName": "set-1",
        "testTagName": "Test2",
        "methodName": "addAccount"
    },
    {
        "setName": "set-2",
        "testTagName": "Test3",
        "methodName": "addRole"
    }
  ]

I use Java. I have the above JSON Array in a Gson object. How do I iterate through this Gson array to check if a particular method name (eg: addRole), exists in the array for the key "methodName" in any of the objects of the JSON array? I am expecting true/false as a result.

I checked the GSON doc - (https://github.com/google/gson/blob/master/gson/src/main/java/com/google/gson/JsonObject.java#L141)

The has method seems to check for the key. I am looking for a method that can iterate through the objects of the array and check if a particular value exists for a specific key.

How can I achieve this?


Solution

  • First you need to deserialize the JSON code to a JsonArray in this way:

    JsonArray jsonArr = gson.fromJson(jsonString, JsonArray.class);
    

    After that you can create this method:

    public boolean hasValue(JsonArray json, String key, String value) {
        for(int i = 0; i < json.size(); i++) {  // iterate through the JsonArray
            // first I get the 'i' JsonElement as a JsonObject, then I get the key as a string and I compare it with the value
            if(json.get(i).getAsJsonObject().get(key).getAsString().equals(value)) return true;
        }
        return false;
    }
    

    Now you can call the method:

    hasValue(jsonArr, "methodName", "addRole");