Skip to content

Lab 7: Return JSON of DTO via GET


  • Return a Data Transfer Object (DTO) as a JSON string
  • Understand the difference between Domain Objects and DTOs
  • Learn more about the Jackson ObjectMapper class

a. Create DTO

  1. Create a new Class, CoffeeItemResponse, that has four instance variables: a long for the id, and four Strings: size, kind, creamer, and price.
  2. Generate getters and setters for all 5 variables.
  3. Write a static factory method, from that takes a CoffeeItem and returns a converted CoffeeItemResponse containing the information from the coffee item.

b. JSON Web Test

  1. Add the following autowired dependency to the CoffeeOrderWebTest:

    ObjectMapper objectMapper;
  2. Add the following test method:

public void getCoffeeOrderIsCompleteJson() throws Exception {
  MvcResult mvcResult = mockMvc.perform(get("/api/coffee/order")

  CoffeeItem coffeeItem = new CoffeeItem("small", "latte", "milk");
  CoffeeItemResponse expectedResponse = CoffeeItemResponse.from(coffeeItem);
  String expectedJson = objectMapper.writeValueAsString(expectedResponse);


Test Fails

Run the above test, and it should compile, but fail.

c. Convert Item to Response

In the CoffeeOrderController change the GET-mapped method to return a CoffeeItemResponse DTO instead of the domain object.


Make sure to use the from method to convert the CoffeeItem object to a DTO, don't just create the DTO directly.

If you do this correctly, the above test should pass.


Now that the test passes, run the application and try it in the browser: http://localhost:8080/api/coffee/order


A class that exposes instance variables as properties via getters and setters.
Data Transfer Object
A DTO is a data-only class following the JavaBean getter/setter naming pattern, used for incoming and outgoing data to be transformed to JSON, XML, and other Media Types.
Response Object
A response object is a DTO that's meant to be returned to the caller of an HTTP API.
Converts JavaBean-style objects to and from JSON, XML, and other formats.