Adam Bien's Weblog

JSON Is The New Data Transfer Object (DTO)

The JSON processing API comes with Java EE 7 and is already integrated with JAX-RS. JsonObject and JsonArray are serialized and deserialized by the JAX-RS runtime without any additional effort.

JsonObject is a Map<String, JsonValue> and so a generic and dynamic DTO.

Because the entities know their state and also have access to private data, the JSON-mapping happens directly within the domain objects:

    
public class Workshop {

    private String name;
    private int duration;

    public Workshop(String name, int duration) {
        this.name = name;
        this.duration = duration;
    }


    public Workshop(JsonObject input) {
        this.name = input.getString("name");
        this.duration = input.
                getJsonNumber("duration").
                intValue();
    }


    public JsonObject toJson() {
        return Json.createObjectBuilder().
                add("name", this.name).
                add("duration", this.duration).
                build();
    }
}
    
    

Now the JAX-RS resource class only has to invoke the entities method to map from and to the JsonObject representation:

        
@Stateless
@Path("workshops")
public class WorkshopsResource {

    @Inject
    RegistrationStore store;

    @GET
    public JsonArray all() {
        JsonArrayBuilder list = Json.createArrayBuilder();
        List<Workshop> all = this.store.all();
        all.stream().map(Workshop::toJson).forEach(list::add);
        return list.build();
    }

    @POST
    public void save(JsonObject input) {
        this.store.save(new Workshop(input));
    }
}
        
    
See you at Java EE Microservices. Is Munich's airport too far? Learn from home: javaeemicro.services.


NEW workshop: HTML 5 and JavaScript Essentials, Three days in April 2017: from Java EE 7 Architectures over Microservices to Performance, Troubleshooting and Monitoring
On demand workshops: Java EE 7: Bootstrap, Effective, Testing and Microservices available for streaming.

Newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

Hi Adam,

This is a nice, neat solution for using JSON in Java EE 7 and I am very much a fan of your "no libraries" ethos however in this case wouldn't it be worth it to use one of the many popular, stable JSON binding frameworks? For example jackson or Gson?

Of course, JSON-B will solve this problem in Java EE 8 but until then isn't a JSON binding library the one dependency that is probably worth breaking the rule for?

Cheers,
Dan

Posted by Daniel Banks on February 06, 2017 at 09:30 AM CET #

That is good. How about serializing/deserializing date types?

Posted by Nazir Bunu on February 06, 2017 at 04:30 PM CET #

Post a Comment:
  • HTML Syntax: NOT allowed
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License