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



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

  1. HttpEntity<String> entity = new HttpEntity<String>(comment, headers);

这里的注释是String类型,头是HttpHeader对象。

  1. ObjectMapper om = new ObjectMapper(); HttpEntity<String> entity = new HttpEntity<String>(om.writeValueAsString(comment), headers);

我只想知道哪一个会更好,为什么。

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

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

那么om.writeValueAsString(new Coordinate(1, 2))将产生类似的东西

{ "x":1,"y":2 }

而不是CCD_ 5方法产生的任何结果。

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

comment:是返回服务器的请求。

headers:注释类型json或xml、html、Image、multipart。。。等

参见此示例:

RestTemplate restTemplate = new RestTemplate();
ObjectMapper mapper = new ObjectMapper();
String requestJson = null;
try {
requestJson = mapper.writeValueAsString(Yourrequest);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);
} catch (JsonGenerationException e) {
LOGGER.error("JsonGenerationException occurred ", e);
} catch (JsonMappingException e) {
LOGGER.error("JsonMappingException occurred ", e);
} catch (IOException e) {
LOGGER.error("IOException occurred ", e);
}

最新更新