Spring 如何从RestTemplate获得格式良好的输出?
下面是我的Spring Boot应用程序的一个服务器调用的响应Spring 如何从RestTemplate获得格式良好的输出?,spring,spring-boot,postman,resttemplate,pretty-print,Spring,Spring Boot,Postman,Resttemplate,Pretty Print,下面是我的Spring Boot应用程序的一个服务器调用的响应 String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody(); 然后我回到客户那里,就像 return ResponseEntity.ok().body(result); 在《邮递员》中,我看到json打印了许多格式相当不错的\“ 我是否需要在响应端进行更改才能在Postman中看到格式良好的输出 邮递员输出样
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\"}]}" ...
预期输出:没有
\“
的情况下格式非常好。最好的方法是创建bean并反序列化该字符串。
之后,您将拥有具有所有优点的结构化对象。(例如,pretty-toString方法)在我看来,
String-result=restemplate.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);
@pvpkiran实际上我想删除
\”
如何做?更新了帖子。如果你提供MWE,它会很有帮助MWE是什么意思?例如?restTemplate.getForObject(url,request,Foo.class)ResponseEntity response=restTemplate.exchange(url,HttpMethod.GET,request,Foo.class);什么是对象映射器?只需@Autowire it@Autowired ObjectMapper ObjectMapper;
尝试使用result=(new ObjectMapper()).readValue(result,String.class);
没有帮助,但您是否可以在发送前打印结果
,在此行之前返回ResponseEntity.ok().body(result);