Create JsonArray from List

user2824073 picture user2824073 · Feb 20, 2014 · Viewed 16.9k times · Source


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

Answer

Nicky Tellekamp picture Nicky Tellekamp · Feb 20, 2014

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;
}