Java 8 + Java EE 7: POJO to JsonObject Conversion

With Java 8 a java.util.List of domain objects can be easily converted into a javax.json.JsonArray using a Collector created by the Collectors utility. javax.json.JsonObject and javax.json.JsonArray have to be created with the corresponding builder, what makes a Collector implementation necessary:

 public JsonArray allAsJson() {
        Collector<JsonObject, ?, JsonArrayBuilder> jsonCollector
                = Collector.of(Json::createArrayBuilder, JsonArrayBuilder::add,
                        (left, right) -> {
                            return left;
        return all().stream().map(Registrations::convert).

    static JsonObject convert(Registration registration) {
        return Json.createObjectBuilder().
                add("price", registration.getTotalPrice()).
                add(CONFIRMATION_ID, registration.getId()).build();

The snippet above is a part of the Java EE 7 / Java 8 sample project and can be easily installed using: mvn archetype:generate -Dfilter=com.airhacks:javaee-bce-archetype.

See you at Java EE Workshops at Munich Airport or on demand and in a location very near you:!


I know a simpler way and no brainer, use Gson

List<Registrations> yourList ....;

String jsonStr = new Gson().toJson(yourList);

and you're done!

Posted by Nestor Hernandez on September 05, 2014 at 02:20 PM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
...the last 150 posts
...the last 10 comments