简体   繁体   中英

How do I convert a JsonArray of JsonString to a List of String

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" .

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/orElse combination 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM