RestTemplate和访问json [英] RestTemplate and acessing json

查看:156
本文介绍了RestTemplate和访问json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过许多其他帖子的回复,但想了解是否有更好的方法来做同样的事情。

I have seen the responses from many other posts but would like to understand if there is a better way to do the same thing.

要求: -
我正在使用restTemplate与Web服务进行通信,该服务返回动态的JSON输出。作为消费者,我不想访问所有领域,但对其中的一些领域感兴趣。我使用Spring框架和Jackson解析器,并找到了访问它的方式

Requirement:- I am using restTemplate to talk to web service which returns JSON output which is dynamic. As a consumer I don't want to access all fields but is interested in few of them. I am using Spring framework with Jackson parser and found the way of accessing it

     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 Object是我不想做的事情,因为json输出不在我的控制中

Do you know any better way to do it? Mapping to java Object is something that I dont want to do as the json output is not in my control

推荐答案

如果你的 RestTemplate 配置了默认 HttpMessageConverters ,由 Jackson2ObjectMapperBuilder提供,您可以直接从 restTemplate.getForObject 获得 JsonNode

If your RestTemplate is configured with the default HttpMessageConverters, which is provided by Jackson2ObjectMapperBuilder, you may directly get a JsonNode from restTemplate.getForObject.

例如,

ArrayNode resources = restTemplate.getForObject("/resources", ArrayNode.class);

或者,

ObjectNode resource = restTemplate.getForObject("/resources/123", ObjectNode.class);

请注意 ArrayNode ObjectNode JsonNode 的子类。

这篇关于RestTemplate和访问json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆