개발/Spring

[Spring] json deserialize ClassCastException

IamBD 2022. 6. 16. 21:04

내부 API 통신 중 T 타입으로 받은 DTO가 해당 DTO 객체가 아닌 LinkedHashMap으로 인식되는 문제를 겪었습니다.

 

LinkedHashMap으로 들어온것을 확인할 수 있음

이유를 찾아보니 WebClient의 bodyToMono(Class<T>) 를 통해 역직렬화시 내부적으로 Jakson 라이브러리를 사용하며

json 데이터를 단순히 List<객체>로 지정시 "객체"가 어떤것인지 명확하게 알지못하기 때문에 기본 타입인 LinkedHashMap으로

변환하게 됩니다.

 

구글링에서 흔히 나오는 간단한 해결 방법은 다음과 같았습니다.

ObjectMapper mapper = new ObjectMapper();
mapper.convertValue(타겟 클래스, new TypeReference<>());

 

하지만 별도의 후처리가 번거롭다면 문제점 자체가 어떤 타입인지 명확히 알지 못하는것이니

Spring 자체에서 제공해주는 방법으로도 해결 가능합니다.

new ParameterizedTypeReference<타겟 타입>() {}

 

ParamerterizedTypeReference 사용
원하는 DTO 객체로 인식되었다.

 

참고

https://www.baeldung.com/jackson-linkedhashmap-cannot-be-cast

 

Jackson: java.util.LinkedHashMap cannot be cast to X | Baeldung

Learn why the "java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to X" exception occurs and how to solve the problem

www.baeldung.com

https://www.baeldung.com/spring-webclient-json-list

 

Get List of JSON Objects with WebClient | Baeldung

Learn how to convert a JSON Array into a Java Array of Object, Array of POJO, and a List of POJO using Spring WebClient

www.baeldung.com

 

'개발 > Spring' 카테고리의 다른 글

InvalidDefinitionException 에러  (0) 2022.06.08
Spring Data JPA - 2  (0) 2022.02.25
Spring Data JPA - 1  (0) 2022.02.24