[spring boot] responseBody MappingJackson2HttpMessageConverter의 convert 원리

junchanpp·2023년 1월 8일
1

spring boot

목록 보기
1/1
post-thumbnail

org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported ERROR 발생

as is

	@GetMapping(value = "/cafe-info", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<CafeInfoResponse> getCafeInfo() {
        return ResponseEntity.ok(new CafeInfoResponse());
    }
public class CafeInfoResponse {
    private int cafeSeq;
}

to be

@Getter
@Setter
public class CafeInfoResponse {
    private int cafeSeq;
}

getter를 추가해주면 된다.


왜 에러가 발생한 것일까?

  • 스프링 가이드를 찾아보면, 스프링 HTTP message converter (MappingJackson2HttpMessageConverter)를 통해 자동으로 객체를 json형태로 변환시킨다.
  • MappingJackson2HttpMessageConverter의 기본 생성자는 Jackson2ObjectMapperBuilder에서 제공하는 기본 구성을 사용한다고 되어있다.
  • Jackson2ObjectMapperBuilder의 getter를 detect하는 설정의 기본값은 아래와 같다.
	@Test
    void test(){
        var objectMapper = Jackson2ObjectMapperBuilder.json().build();

        Assertions.assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
        Assertions.assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
        //objectMapper.getVisibilityChecker() 통해서도 확인 가능
    }

참고자료

https://spring.io/guides/gs/rest-service/
https://fasterxml.github.io/jackson-databind/javadoc/2.10/com/fasterxml/jackson/databind/MapperFeature.html#AUTO_DETECT_GETTERS
https://fasterxml.github.io/jackson-databind/javadoc/2.10/com/fasterxml/jackson/databind/MapperFeature.html

0개의 댓글