【问题标题】:How to get pretty formatted output from RestTemplate?如何从 RestTemplate 获得格式化的输出?
【发布时间】:2020-07-01 09:06:31
【问题描述】:

以下是我的 Spring Boot 应用程序中的一个服务器调用的响应,

String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();

然后我会回到客户那里,

return ResponseEntity.ok().body(result);

在邮递员中,我看到 json 打印有许多 \",格式相当漂亮。

我是否需要更改响应方才能在 Postman 中看到格式精美的输出?

邮递员输出示例:

"{\"records\":[{\"pkg_name\":\"com.company.app\",\"start_time\":1580307656040,\"update_time\":12345,\"min\":0.0,\"create_time\":1580307714254,\"time_offset\":21600000,\"datauuid\":\"xyz\",\"max\":0.0,\"heart_beat_count\":1,\"end_time\":1580307656040,\"heart_rate\":91.0,\"deviceuuid\":\"abc\"}]}" ...

预期输出:没有\"的格式很漂亮

【问题讨论】:

标签: spring spring-boot postman resttemplate pretty-print


【解决方案1】:

最好的方法是创建 bean 并将这个 String 反序列化到它。 之后,您将拥有具有所有好处的结构化对象。 (例如漂亮的 toString 方法)

【讨论】:

  • 如果你提供 MWE 会很有帮助
  • MWE 是什么意思?例子? restTemplate.getForObject(url, request, Foo.class)
  • ResponseEntity response = restTemplate .exchange(url, HttpMethod.GET, request, Foo.class);
【解决方案2】:

在我看来 String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody(); 返回双编码的 json 字符串。取消转义并获得正常的 json

 String unwrappedJSON = objectMapper.readValue(result, String.class);
 return ResponseEntity.ok().body(unwrappedJSON);

编辑

如果结果是正常的 json 并且没有双重转义,则可以尝试:

JsonNode result = restTemplate.exchange(url, HttpMethod.GET, entity, JsonNode.class).getBody();

return ResponseEntity.ok().body(result);

【讨论】:

  • 什么是对象映射器?
  • 只需@Autowire 它@Autowired ObjectMapper objectMapper;
  • 尝试使用result = (new ObjectMapper()).readValue(result, String.class); 并没有帮助
  • 发送前可以打印result
  • 在这行之前return ResponseEntity.ok().body(result);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 2021-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多