首页 > 解决方案 > 如何从 RestTemplate 获得格式化的输出?

问题描述

下面是我的 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\"}]}" ...

预期输出:格式很好,没有\"

标签: springspring-bootpostmanresttemplatepretty-print

解决方案


在我看来,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);

推荐阅读