Spring Framework

FeignClient DecodeException JsonToken.START_OBJECT

Junuuu 2023. 11. 27. 00:01

 

개요

FeignClient를 사용하다 실수한 부분을 파악하고 공유해보고자 합니다.

 

 

에러발생

feign.codec.DecodeException:
Error while extracting response for type [java.util.List<com.example.study.dto.Profile>]
and content type [application/json]] with root cause
com.fasterxml.jackson.databind.exc.MismatchedInputException:
Cannot deserialize value of type `java.util.ArrayList<com.example.study.dto.Profile>` 
from Object value (token `JsonToken.START_OBJECT`)

DecodeException이 발생하였고, 주된 내용으로는 JsonToken.START_OBJECT입니다.

 

https://www.baeldung.com/jsonmappingexception-can-not-deserialize-instance-of-java-util-arraylist-from-object-value-token-jsontoken-start_object

 

해당 예외에 대해 찾아보면 list는 {}가 아닌 []로 파싱해야 한다고 정리되어 있습니다.

 

응답을 받는 부분

@FeignClient(
    name = "localTestFeign",
    url = "http://localhost:8080",
)
interface LocalFeignClient {

    @GetMapping("/internal-call")
    fun getProfiles(): List<Profile>
}

 

응답을 내려주는 부분

@RestController
class InternalCallController {

    @GetMapping("/internal-call")
    fun internalCall(request: HttpServletRequest): ResponseEntity<ProfileResponse>{
        return ResponseEntity.ok(ProfileResponse(listOf(ProfileDTO("1","2"))))
    }
}

 

 

ProfileResponse

data class ProfileResponse(
    val profiles: List<ProfileDTO>
)

data class ProfileDTO(
    val col1: String,
    val col2: String,
)

 

 

Profile

data class Profile(
    val col1: String,
)

 

 

응답을 내려주는 부분은 ProfileResponse로 내부에 List를 가지지만 응답을 받는 부분에는 List<Proifle>로 리스트가 밖에 있기 때문에 Decode시 예외가 발생한 것입니다.

 

예외가 발생하지 않도록 래핑

data class ClientProfileResponse(
    val profiles: List<Profile>
)

 

이제 더 이상 예외가 발생하지 않습니다.