如何使用Jackson ObjectMapper和Spring的RestTemplate处理各种响应?

时间:2015-08-06 12:33:08

标签: java json spring rest jackson

我正在使用Spring的RestTemplate和Jackson ObjectMapper来使用REST服务。问题是如果有错误,那么返回的JSON与我期望的对象完全不同,因此它失败了。另外我甚至不能使用String.class,因为这会引发类似的错误。我甚至不知道响应是什么样的,因为实际请求会引发异常,所以我从来没有得到能够检查的响应。

这里有一些代码:

    String url = BASE_URL + USER_LOGIN_URL;

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    MultiValueMap<String, String> postData = new LinkedMultiValueMap<String, String>();
    // Postdata added here

    HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(postData, headers);

        UserInfo userInfo = restTemplate.postForObject(url, entity, UserInfo.class); // Doesn't work if not UserInfo

        // ** OR THE FOLLOWING **


        String response = restTemplate.postForObject(url, entity, String.class);
        logger.debug(response); // Never reaches here because ObjectMapper seems to expect a JSON object named "String"
        UserInfo userInfo = objectMapper.readValue(response, UserInfo.class);

1 个答案:

答案 0 :(得分:1)

I think RestTemplate uses a DefaultResponseErrorHandler for handling error responses (code beginning with 4 or 5). That throws an instance of HttpStatusCodeException with a method getResponseBodyAsString().

So, you can catch that exception and extract the response as a String.