何时使用ObjectMapper类的writeValueAsString()方法以及何时直接使用String

时间:2017-08-31 10:39:23

标签: java spring rest

在我的项目中有两种类型的代码:

  1. HttpEntity<String> entity = new HttpEntity<String>(comment, headers);
  2. 这里的注释是String类型,头是HttpHeader Object。

    1. ObjectMapper om = new ObjectMapper(); HttpEntity<String> entity = new HttpEntity<String>(om.writeValueAsString(comment), headers);
    2. 我只想知道哪一个更好,为什么。 感谢您提前帮助

2 个答案:

答案 0 :(得分:1)

writeObjectAsString将其写为JSON格式的字符串。例如,如果我有一个类Coordinate,它看起来像:

class Coordinate {
  private int x;
  private int y;
  // plus constructor and methods
}

然后om.writeValueAsString(new Coordinate(1, 2))将产生类似

的内容
{ "x":1,"y":2 }

而不是toString方法产生的任何内容。

因此,当您的客户端期望JSON格式的字符串时,请使用ObjectMapper.writeValueAsString

答案 1 :(得分:0)

评论:是要求在服务器中发送。

标题:评论类型json或xml,html,Image,multipart ...等。

见这个例子:

RestTemplate restTemplate = new RestTemplate();
    ObjectMapper mapper = new ObjectMapper();
    String requestJson = null;
    try {
        requestJson = mapper.writeValueAsString(Yourrequest);
    } catch (JsonGenerationException e) {
        LOGGER.error("JsonGenerationException occurred ", e);

    } catch (JsonMappingException e) {
        LOGGER.error("JsonMappingException occurred ", e);
    } catch (IOException e) {
        LOGGER.error("IOException occurred ", e);
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<Object> entity = new HttpEntity<Object>(requestJson, headers);
    LOGGER.info("send request to  url {} ", getUrl());
    YourTypeOfResponse response = restTemplate.postForObject(URL_LOCAL,
            entity, YourTypeOfResponse.class);
相关问题