AutoTester999
AutoTester999

Reputation: 616

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?

Upvotes: 2

Views: 23188

Answers (2)

Vini
Vini

Reputation: 8419

You can get the JSON in a JsonArray and then iterate over the elements while checking for the desired value.

One approach is suggested by @Crih.exe above. If you want to use Streams, you can convert the JsonArray into a stream and use anyMatch to return a boolean value

...
// Stream JsonArray
Stream<JsonElement> stream = StreamSupport.stream(array.spliterator(), true);

// Check for any matching element
boolean result = stream.anyMatch(e -> e.getAsJsonObject()
                   .get("methodName").getAsString().equals("addRole"));

System.out.println(result);
...

Upvotes: 3

Crih.exe
Crih.exe

Reputation: 524

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

Upvotes: 5

Related Questions