Java Spring restTemplate 获取原始 json 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47104149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 02:33:42  来源:igfitidea点击:

Spring restTemplate get raw json string

javajsonspringspring-mvcspring-rest

提问by suraj bahl

How can I get the raw json string from spring rest template? I have tried following code but it returns me json without quotes which causes other issues, how can i get the json as is.

如何从 spring rest 模板中获取原始 json 字符串?我试过下面的代码,但它返回我没有引号的 json,这会导致其他问题,我怎样才能按原样获取 json。

ResponseEntity<Object> response  = restTemplate.getForEntity(url, Object.class);
String json = response.getBody().toString();

采纳答案by madhead

You don't even need ResponseEntitys! Just use getForObjectwith a String.classlike:

你甚至不需要ResponseEntitys!只需getForObjectString.class喜欢一起使用:

final RestTemplate restTemplate = new RestTemplate();
final String response = restTemplate.getForObject("https://httpbin.org/ip", String.class);

System.out.println(response);

It will print something like:

它将打印如下内容:

{
  "origin": "1.2.3.4"
}