diff --git a/json-modules/json-arrays/pom.xml b/json-modules/json-arrays/pom.xml new file mode 100644 index 0000000000..0eefbc86fc --- /dev/null +++ b/json-modules/json-arrays/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + org.baeldung + json-arrays + json-arrays + + + com.baeldung + json-modules + 1.0.0-SNAPSHOT + + + + + org.json + json + ${json.version} + + + com.google.code.gson + gson + ${gson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + javax.json.bind + javax.json.bind-api + ${jsonb-api.version} + + + + + 1.0 + 20230227 + 2.8.5 + 1.1.2 + 2.28.0 + + + diff --git a/json-modules/json-arrays/src/test/java/com.baeldung.checkforkey/CheckForKeyUnitTest.java b/json-modules/json-arrays/src/test/java/com.baeldung.checkforkey/CheckForKeyUnitTest.java new file mode 100644 index 0000000000..6e1cbb7ab0 --- /dev/null +++ b/json-modules/json-arrays/src/test/java/com.baeldung.checkforkey/CheckForKeyUnitTest.java @@ -0,0 +1,47 @@ +package com.baeldung.checkforkey; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Objects; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; + +public class CheckForKeyUnitTest { + + private final String exampleJson = "[{\"colour\":\"red\"},{\"colour\":\"blue\"},{\"colour\":\"green\"}]"; + + @Test + public void givenJsonArray_whenUsingJackson_thenDetectKeyInArray() throws JsonProcessingException { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode tree = objectMapper.readTree(exampleJson); + + Stream s = StreamSupport.stream(tree.spliterator(), false); + boolean result = s.map(entry -> entry.get("colour")) + .filter(Objects::nonNull) + .anyMatch(colour -> "green".equals(colour.asText())); + assertTrue(result); + } + + @Test + public void givenJsonArray_whenUsingGson_thenDetectKeyInArray() { + Gson gson = new Gson(); + JsonArray parsed = gson.fromJson(exampleJson, JsonArray.class); + + Stream s = StreamSupport.stream(parsed.spliterator(), false); + boolean result = s.map(entry -> entry.getAsJsonObject() + .get("colour")) + .filter(Objects::nonNull) + .anyMatch(colour -> "green".equals(colour.getAsString())); + assertTrue(result); + } + +} diff --git a/json-modules/pom.xml b/json-modules/pom.xml index 82314e0edf..306b404049 100644 --- a/json-modules/pom.xml +++ b/json-modules/pom.xml @@ -16,6 +16,7 @@ json json-2 + json-arrays json-conversion json-path gson