Search code examples
jsonkotlinjacksonresttemplate

How do I correctly deserialize json that consists of a list item that includes another object?


The client I am using returns json like this:

[
    {
        "source": "ANY"
    }
]

That is, the element of the array that the object is in.

I'm trying to make a request like this:

restTemplate.postForObject<AbcdResponse>(
    "/address",
    listOf(value).let { JsonHttpEntity(it) }
)
data class AbcdResponse(
    val obj: AbcdObject
)
data class DaDataAddress(
    val source: String?
)

But I get the HttpMessageNotReadableException exception:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.app.client.abcd.domain.AbcdResponse` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.app.client.abcd.domain.AbcdResponse` out of START_ARRAY token
 at [Source: (ByteArrayInputStream); line: 1, column: 1]

How can I deserialize the response correctly?


Solution

  • As you probably noticed, the response as a whole is a JSON array. You can tell by the square brackets [ ... ] surrounding the whole thing.

    Because of this, you cannot deserialize it as an object (such as AbcdResponse). What you should do instead is use List<DaDataAddress> instead of AbcdResponse.