Skip to content

Lab 6: Return JSON of DTO via GET

Goals

  • 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:

    // in tests, it's OK to do "field" Autowiring (injection)
    @Autowired
    ObjectMapper objectMapper;
    
  2. Add this new test method:

    @Test
    public void getCoffeeOrderReturnsCompleteJson() throws Exception {
      MvcResult mvcResult = mockMvc.perform(get("/api/coffee/order")
                                                .accept(MediaType.APPLICATION_JSON))
                                   .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                                   .andReturn();
    
      CoffeeItem coffeeItem = new CoffeeItem("small", "latte", "milk");
      coffeeItem.setId(1L);
      CoffeeItemResponse expectedResponse = CoffeeItemResponse.from(coffeeItem);
      String expectedJson = objectMapper.writeValueAsString(expectedResponse);
    
      assertThat(mvcResult.getResponse().getContentAsString())
          .isEqualTo(expectedJson);
    }
    

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.

Note

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.

Browser

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

Is that what you expected to see?


Glossary

JavaBean
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-based Web API.
ObjectMapper
Part of the Jackson library. Converts JavaBean-style objects to and from JSON, XML, and other formats.