Create JsonArray from list


I need to create a javax.json.JsonArray object (Java EE 7 API) from java.util.List from JsonObjects. Previously, when using the JSON API, I used this simply:

JSONArray jsonArray = new JSONArray(list);

But I do not see any equivalent constructor in javax.json.JsonArray there. Is there an easy way (besides viewing all the lists) to do this?
Thanks

+3
source share
2 answers

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

I don’t know what your list looks like, but you can 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;
}
+9
source

If anyone is wondering how to do this with Java 8 threads. 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;
}
0
source

All Articles