ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • HTTP 메시지 컨버터 : JSON
    SPRING/스프링 MVC 2021. 6. 18. 16:41

     

     

    스프링 부트를 사용하지 않는 경우(SPRING MVC)에는 사용하고 싶은 JSON 라이브러리를 의존성으로 추가

    - GSON 

    - JacksonJSON 

    - JacksonJSON 2 

     

    스프링 부트를 사용하는 경우 

    - 기본적으로 spring-boot-starter-web에 JacksonJSON 2가 의존성으로 들어있다. 

    - , JSONHTTP 메시지 컨버터가 기본으로 등록되어 있다

    @RestController
    public class SampleController {
    
        @GetMapping("/jsonMessage")
        public Person jsonMessage(@RequestBody Person person) {
            return person;
        }
    
    }
    

    POSTMAN 테스트

     

     

    테스트코드

    @RunWith(SpringRunner.class)
    @SpringBootTest
    @AutoConfigureMockMvc
    public class SampleControllerTest {
    
        @Autowired
        MockMvc mockMvc;
        @Autowired
        ObjectMapper objectMapper;
    
        @Test
        public void jsonMessage() throws Exception {
    
            Person person = new Person();
            person.setId(2019l);
            person.setName("jump");
            String jsonString = objectMapper.writeValueAsString(person);
    
            this.mockMvc.perform(get("/jsonMessage")
                    .contentType(MediaType.APPLICATION_JSON_UTF8)
                    .accept(MediaType.APPLICATION_JSON_UTF8)
                    .content(jsonString))
                    .andDo(print()) // 요청과 응답을 출력
                    .andExpect(status().isOk());
    
        }
    
    }

    'SPRING > 스프링 MVC' 카테고리의 다른 글

    기타 WebMvcConfigurer 설정  (0) 2021.06.19
    HTTP 메시지 컨버터 : XML  (0) 2021.06.19
    HTTP 메시지 컨버터 : 개요  (0) 2021.06.18
    Resource Handler  (0) 2021.06.16
    HandlerInterceptor (서블릿 필터 비교)  (0) 2021.06.15
Designed by Tistory.