adam bien's blog

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.