본문 바로가기
BackEnd/Spring

[Spring] com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class 오류 해결

by 성은2 2023. 2. 28.

오류

com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.example.dto.ResponseCodeDto and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.HashMap["responseCodeDto"])

 

 

해결

// 생략... 
responseMap.put("body", new Gson().toJson(responseCodeDto));

// return
return responseMap;

responseCodeDto를 JSON으로 변환해서 return 할 때 만난 오류다.(Gson 라이브러리 사용)

 

해결 방법은 Json으로 변환하려는 해당 dto에 getter 메서드를 만들어주거나, 해당 dto의 필드를 public으로 접근 제한자를 변경 하는것이다.

(lombok 사용시 @Getter 혹은 @Data 어노테이션을 사용해 문제해결)

 

 

이유는 다음과 같다.

기본적으로 Jackson2는 공개 필드 또는 공개 getter 메서드가 있는 필드에서만 작동합니다. 모든 필드가 비공개 또는 패키지 비공개인 엔터티를 직렬화하면 실패합니다.