4


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

5
  • 1
    The javadoc contains examples... Commented Feb 20, 2014 at 13:23
  • What is list in this example? Commented Feb 20, 2014 at 13:24
  • Already checked. But Javadocs contains the following example:JsonArray value = Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("number", "212 555-1234")) .add(Json.createObjectBuilder() .add("type", "fax") .add("number", "646 555-4567")) .build(); This is not what I have asked- I already have a List<JsonObjects> Commented Feb 20, 2014 at 13:27
  • i didn't know there was a json package within Java. Commented Feb 20, 2014 at 13:28
  • @Sikorski in Java EE only Commented Feb 20, 2014 at 13:29

2 Answers 2

10

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It seems that's the only way to do it.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.