Jackson - Deserializing JSON to class

问题: I am calling an endpoint which returns JSON that that looks something like this (in Postman): { "Result": { "attribute1": { ... }, "attribute2": { ......

问题:

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.


回答1:

By default MappingJackson2HttpMessageConverter is bind to:

  • application/json
  • application/*+json

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);
  • 发表于 2019-03-23 04:41
  • 阅读 ( 207 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除