adam bien's blog

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) -> {
                            left.add(right);
                            return left;
                        });
        return all().stream().map(Registrations::convert).
                collect(jsonCollector).build();

    }
	
    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 https://github.com/AdamBien/javaee-bce-archetype 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: airhacks.io!