Question


I'd need to create a javax.json.JsonArray object (Java EE 7 API) from a java.util.List of JsonObjects. Formerly, when using JSON API I used to do it simply with:

JSONArray jsonArray = new JSONArray(list);

But I can see there's no equivalent constructor in javax.json.JsonArray. Is there a simple way (other than browsing across all the List) to do it ?
Thanks

Was it helpful?

Solution

Unfortunately the standard JsonArrayBuilder does not take a list as input. So you will need to iterate over the list.

I don't know how your List looks but you could make a function like:

public JsonArray createJsonArrayFromList(List<Person> list) {
    JsonArray jsonArray = Json.createArrayBuilder();
    for(Person person : list) {
        jsonArray.add(Json.createObjectBuilder()
            .add("firstname", person.getFirstName())
            .add("lastname", person.getLastName()));
    }
    jsonArray.build();
    return jsonArray;
}

OTHER TIPS

If someone is interessted in how to do this with Java 8 Streams. The same code snippet:

public JsonArray createJsonArrayFromList(List<Person> list) {
    JsonArray jsonArray = Json.createArrayBuilder();
    list.stream().forEach(person -> jsonArray.add(Json.createObjectBuilder()
            .add("firstname", person.getFirstName())
            .add("lastname", person.getLastName())));
    jsonArray.build();
    return jsonArray;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top