본문 바로가기
카테고리 없음

ResponseEntity와 Jackson과 Getter

by 수수남매 2023. 11. 6.

GlobalExceptionHandler를 만들면서 ResponseEntity에 custom한 ErrorResponse를 실어서 보내고 있었다.

그런데 자꾸 failed in @ExceptionHandler와 HttpMediaTypeNotAcceptableException이 발생하는 것이다!!

 

이걸 해결해 보려고 이틀 동안 뒤져봤는데.. 허탈하게도 이유는 너무 단순했다.

내가 custom한 ErrorResponse 클래스에 Getter를 주지 않았던 것...

ResponseEntity에서 body로 들어온 객체를 JSON으로 변경하기 위해 Jackson라이브러리에서 등록된 MessageConverter를 호출했고, 이 놈은 Getter/Setter property를 기준으로 작동하는데 ErrorResponse객체에 Getter/Setter가 없으니 멘붕이 왔겠지... 그래 내가 미안하다...

추가로 Getter/Setter가 아니더라도 @JsonProperty, @JsonAutoDetect를 사용해 클래스 필드를 프로퍼티로 지정할 수 있다고 한다.

public class Person {
    @JsonProperty("name")
    private String myName = "Mommoo";
}

@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class Person{
    private String myName = "Mommoo";
}

출처: https://mommoo.tistory.com/83 [개발자로 홀로 서기:티스토리]

 

참고자료

https://mommoo.tistory.com/83