SpringBoot/오류
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "필드명"
se0nghyun2
2023. 1. 3. 21:35
원인?
JSON데이터를 DTO객체로 매핑 시 선언되지 않은 필드가 존재할 경우 아래와 같은 에러가 발생한다.
(=JSON내 특정 프로퍼티 존재하나 DTO객체 내 해당 필드가 선언되지 않은 경우)
더보기
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "logo"
예시
특정 API 응답으로 JSON 데이터에 resultCode, resultMessage 프로퍼티가 있다고 가정한다.
{
resultCode : "0",
resultMessage : "success"
}
그런데 ObjectMapper 사용하여 응답받은 JSON데이터를 내가 정의한 DTO클래스로 매핑 시
아래와 같이 resultMessage 필드가 존재하지 않을 경우 위와 같은 에러가 발생한다.
public class ResponseDTO {
private String resultCode;
}
// APIService.java파일 내 통신 로직
HttpClient httpClient = HttpClientBuilder.create().build();
HttpResponse httpResponse = httpClient.execute(new HttpGet(uri));
HttpEntity entity = httpResponse.getEntity();
content = EntityUtils.toString(entity);
ResponseDTO responseDTO = objectMapper.readValue(content, responseDTO.class); //에러 발생
해결
1. ObjectMapper Featuer 설정
/*
* 응답 json 객체에 존재하지 않는 필드는 매핑 제외
*/
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
=> JSON 데이터 내 프로퍼티들을 강제하기 않기에 적절한 사용이 필요해 보인다.
2. DTO클래스에 @JsonIgnoreProperty(ignoreUnknown = true) 추가