【问题标题】:Spring restTemplate get raw json stringSpring restTemplate 获取原始 json 字符串
【发布时间】:2018-04-16 16:19:28
【问题描述】:

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

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

【问题讨论】:

  • 你能把例子打印出来吗?
  • 你试过使用String吗? restTemplate.getForEntity(url, String.class);

标签: java json spring spring-mvc spring-rest


【解决方案1】:

你甚至不需要ResponseEntitys!只需将getForObjectString.class 一起使用即可:

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

System.out.println(response);

它将打印如下内容:

{
  "origin": "1.2.3.4"
}

【讨论】:

  • 我的返回类型是对象,我想要原始的 json 字符串?
  • 当服务器将application/json 作为内容类型Cannot deserialize instance of java.lang.String out of START_ARRAY token 发送时,这不会起作用,如果正文只包含一个json-string,它只会给你一个字符串
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-29
  • 2012-06-01
  • 1970-01-01
  • 2016-06-11
  • 2014-12-27
  • 1970-01-01
相关资源
最近更新 更多