0

This question is scoped to The Java API for JSON Processing (JSR 353).

Given a JsonArray whose elements are JsonString, how can I easily convert this to a List<String> or a Set<String>? For Set<String>, let's assume that the JsonArray contains a unique collection of string values.

Assume I have a JSON object like this:

{
  "name" : "James Johns",
  "street" : "22 Nancy St.",
  "emails" : [
               "james@a.com",
               "james@b.net",
               null,
               ""
             ]
}

I want my resulting collection to ignore any null or empty string entries in the emails array.

Let's assume my JsonObject instance has already been created.

JsonObject person = <parse the JSON input>;
JsonArray emails = person.get("emails");

I keep getting stumped on JsonValue and JsonString and trying to get the actual String value. If I use the JsonValue.toString() and JsonString.toString() methods, I get string values that include the double quotes, as if the original JSON was "\"james@a.com\"". I need the string values to be the equivalent JSON value "james@a.com".

John Czukkermann
  • 539
  • 1
  • 4
  • 13
  • Possible answer to your question: [Convert Json Array to normal Java list](https://stackoverflow.com/questions/3395729/convert-json-array-to-normal-java-list). – LHCHIN Dec 16 '19 at 04:42
  • Wouldn't you agree that the Java8 technique I described is cleaner and easier to understand that having to null check the array and then use a brute force indexing for loop? It turns out there is an answer supplied that is similar to mine, but it is pretty far down the list. I created this post in the hopes it will help new inquiries. I searched a long time looking for a solution and never found the one you linked. Thank you for your comment @LHCHIN – John Czukkermann Dec 17 '19 at 15:00
  • Hi, I just provided a possible solution I found to your QUESTION not to your ANSWER as a reply. And I also agreed that Java 8's solution is better! : ) – LHCHIN Dec 18 '19 at 00:29

1 Answers1

0

Using Java 8, one can easily convert a JsonArray of JsonString to a List like this:

JsonObject person = <parse the JSON input>;

List<String> emailList = 
    Optional.ofNullable(person.getJsonArray("emails"))
            .orElse(JsonValue.EMPTY_JSON_ARRAY) // Use an empty list if the property's value was null
            .getValuesAs(JsonString::getString) // Get each JsonString entry as String
            .stream()                           // Turn the collection into a stream for filter/collect
            .filter(email -> email!=null && !email.isEmpty())  // Exclude any null/empty entries
            .collect(Collectors.toList());                     // Create the List

  • The ofNullable/orElsecombination guarantees I get a JsonArray back, even if that array is empty, thus avoiding any Null Pointer Exception considerations.
  • The getValuesAs(JsonString::getString) is a JsonArray method that returns a List by applying the JsonString.getString() method to each returned JsonString. The JsonString.getString() method returns the string value "james@a.com" instead of the "\"james@a.com\"" value that the JsonString.toString() method returns.
  • The stream() method turns the collection into a sequential stream that we can use to filter and collect members of the original collection.
  • The filter() method applies the Predicate email -> email!=null && !email.isEmpty() to each entry in the stream, throwing out any null entries or entries that are empty strings.
  • And finally, the collect() method collects the filtered entries into the specified collection type.

To obtain a Set<String>, change the .collect() to use:

.collect(Collectors.toSet())

Once you get accustomed to the Java 8 mechanics, this approach provides a concise, easy to read and understand technique for manipulating collections without the more complicated approach of null/empty checking and using for loops.

John Czukkermann
  • 539
  • 1
  • 4
  • 13