SPRING/스프링 MVC

HTTP 메시지 컨버터 : JSON

JUMP개발자 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());

    }

}