Reputation: 1051
I am calling an endpoint which returns JSON that that looks something like this (in Postman):
{
"Result": {
"attribute1": { ... },
"attribute2": { ... }
}
}
The Content-Type header returned by this request is text/x-json
(as opposed to the usual application/json
). I think this is causing some problems when trying to deserialize this through Jackson. The POJO for this JSON looks something like this:
@Getter
@Setter
public class Response {
@JsonProperty("Result")
private Result result;
}
The Result
class is from an external library (the same guys who wrote this endpoint). Either ways, when I try to call this endpoint through RestTemplate.exchange()
, Jackson is unable to deserialize this JSON into a valid Result
class. I am doing this:
ResponseEntity<Response> response = restTemplate.exchange(url, HttpMethod.GET, null, Response.class);
Doing response.getBody()
gives a Response
object which contains a null Result
object. Apparently, Jackson is not deserializing the JSON properly. I suspect this is because of the unusual text/x-json
Content-Type returned by the API.
I also have my MappingJackson2HttpMessageConverter
object configured to be able to parse text/x-json
Content-type, but no luck:
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
jsonConverter.setSupportedMediaTypes(ImmutableList.of(new MediaType("text", "x-json")));
restTemplate.getMessageConverters().add(jsonConverter);
Any pointers?
Update: I don't know why this didn't work, but I figured out an alternative way - fetching the JSON as Map
instead of a domain object, which is good enough for my purposes.
Upvotes: 2
Views: 519
Reputation: 38625
By default MappingJackson2HttpMessageConverter
is bind to:
We need to add text/x-json
.
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
List<MediaType> jsonTypes = new ArrayList<>(jsonConverter.getSupportedMediaTypes());
jsonTypes.add(new MediaType("text", "x-json"));
jsonConverter.setSupportedMediaTypes(jsonTypes);
Now, we should use it in RestTemplate
:
restTemplate.setMessageConverters(Collections.singletonList(jsonConverter));
ResponseEntity<RequestPayload> response = restTemplate.exchange(url, HttpMethod.GET, null, RequestPayload.class);
Upvotes: 2