Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JsonArray from List


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

like image 447
user2824073 Avatar asked Dec 25 '22 13:12

user2824073


1 Answers

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;
}
like image 137
Nicky Tellekamp Avatar answered Jan 08 '23 20:01

Nicky Tellekamp