spring - 如何从 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\"}]}" ...
预期输出:格式很好,没有\"
解决方案
在我看来,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);
推荐阅读
- c++ - c++,当我向用户提供我的共享库时,应该提供哪些头文件?
- javascript - 如何访问对象上的子键值并克隆该对象
- javascript - 为什么我的单选按钮的选中属性保持不变,即使状态发生变化(反应)
- c# - 在 ASP.NET WebForms 中一次显示一个重复器中的图像
- android - RecyclerView - 字母索引未出现
- r - 根据条件为字符串添加前缀
- c# - C#/WinForms 工具提示停止显示
- sql - SQL 按日期组合所有数据
- vue.js - vue.js 中是否存在布局的概念?
- mysql - MySQL WHERE LIKE 语句:如何删除表中列子字符串不等于所需子字符串的行?