【发布时间】:2014-09-03 00:03:40
【问题描述】:
我已经看到许多其他帖子的回复,但想了解是否有更好的方法来做同样的事情。
要求:- 我正在使用 restTemplate 与返回动态 JSON 输出的 Web 服务对话。作为消费者,我不想访问所有领域,但对其中的一些领域感兴趣。我正在使用带有 Jackson 解析器的 Spring 框架并找到了访问它的方法
String response = restTemplate.getForObject(targetUrl, String.class);
System.out.println(response);
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(response, JsonNode.class);
JsonNode uri = rootNode.get("uri");
System.out.println(uri.asText());
你知道更好的方法吗?映射到 java 对象是我不想做的事情,因为 json 输出不在我的控制范围内
【问题讨论】:
-
你的方法看起来不错。请注意,只需执行 restTemplate.getForObject(targetUrl, JsonNode.class) 假设您的 restTemplate 已配置为与 Jackson 一起使用。
-
"restTemplate 配置为与 Jackson 一起使用" 你能澄清一下吗?
-
你可以为你的rest模板设置一个HttpMessageCoverter,它将JSON转换为java对象。看看这个问题的示例代码:stackoverflow.com/questions/21355450/…
-
创建 RestTemplate 对象时不存在吗?我看到它已经设置了转换器列表
-
在这里使用
ObjectMapper是多余的。正如 Alexey 所说,您可以使用com.fasterxml.jackson.databind.JsonNode作为restTemplate.getForObject()方法的第二个参数。
标签: json spring jackson resttemplate