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!

Comments:

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
License