Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll learn how to inspect a JSON array and confirm whether a particular key is present and if it has a specific value. We’ll use two of the most popular Java libraries for processing JSON: Jackson and Gson.

2. Setup

First, let’s create a JSON array. We’ll keep it simple and have an array of objects with a single key/value pair each:

String exampleJson = "[{\"color\":\"red\"},{\"color\":\"blue\"},{\"color\":\"green\"}]";

So, each object in the array has the same property color and a different value. For our examples, we’ll check if, for the key color, the value green exists.

3. Using Jackson

To use Jackson in our project, we’ll need to import it into our pom.xml:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version>
</dependency>

The latest version is available in the Maven Repository.

Let’s now use that to solve our problem:

@Test
void givenJsonArray_whenUsingJackson_thenDetectKeyInArray() throws JsonProcessingException {
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode tree = objectMapper.readTree(exampleJson);

    Stream<JsonNode> s = StreamSupport.stream(tree.spliterator(), false);
    boolean result = s.map(entry -> entry.get("color"))
      .filter(Objects::nonNull)
      .anyMatch(color -> "green".equals(color.asText()));
    assertTrue(result);
}

Our first goal is to parse the JSON. For this, we’ve used ObjectMapper. We used the readTree() method to convert our JSON String into a JsonNode.

Following that, we converted our JsonNode into a Stream. We did this using the StreamSupport class, which contains a collection of utilities for creating and working with Streams. The specific utility we used here is the stream() method, which takes a Spliterator and a boolean flag. The flag allows us to choose between a sequential and parallel Stream.

After that, with our Stream ready, we inspected each JsonNode in turn. We needed to be slightly careful here. We have no confirmation that our input JSON has any keys called color. This could result in a NullPointerException when converting the value to a String for comparison.

So first, we attempted to get the property, then filtered to remove any nulls that would occur if the JsonNode had no keys called color. Once we were confident we had our value, we could call anyMatch(). We gave it a predicate comparing each value against our chosen color green.

The anyMatch() method returns true if there is a match. Therefore, our assertion at the end of our test shows that there was a value that equaled green for the selected key color.

4. Using Gson

Next, we’ll take a very similar approach using the Gson library. To use Gson in our project we’ll need to import it into our pom.xml:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

The latest version is available in the Maven Repository.

We’ll apply the same plan here of parsing our JSON String, converting it into a Stream, and using anyMatch() to look for our value:

@Test
void givenJsonArray_whenUsingGson_thenDetectKeyInArray() {
    Gson gson = new Gson();
    JsonArray parsed = gson.fromJson(exampleJson, JsonArray.class);

    Stream<JsonElement> s = StreamSupport.stream(parsed.spliterator(), false);
    boolean result = s.map(entry -> entry.getAsJsonObject()
      .get("color"))
      .filter(Objects::nonNull)
      .anyMatch(color -> "green".equals(color.getAsString()));
    assertTrue(result);
}

Firstly, we parsed our String with the fromJson() method, which gave us a JsonArray. We got the JsonArray type thanks to the second argument, where we could specify the class we wanted to parse the JSON into.

Following that step, the rest should look familiar. We used the StreamSupport utilities as before to produce a Stream of JsonElements. The only other variation is that we needed to call getAsJsonObject() on our JsonElement. This allowed us to retrieve the value associated with the color property and compare it to our String.

As can be seen again here, the match is successfully found in the Stream. Notably, we took the same precautions as before against the potential NullPointerException from having no properties called color in the JSON. If we could have more certainty about which properties would be available, we could skip straight to the anyMatch() step.

5. Conclusion

In this article, we saw that we can use both Jackson and Gson to check if a value exists for a selected property in a JSON array. Both implementations were similar. They ultimately implemented the plan of parsing the JSON, converting it to a Stream, and then finally using the Stream utilities to check for a match. Once we had the Stream, we could have used any number of comparison methods to evaluate the entries in the arrays making this a versatile solution.

As always, the full code for the examples is available over on GitHub.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.