RestTemplate and acessing json

爱⌒轻易说出口 提交于 2019-12-06 03:55:33

问题


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.

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());

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


回答1:


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

For example,

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

Or,

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

Note that ArrayNode and ObjectNode are sub-classes of JsonNode.



来源:https://stackoverflow.com/questions/24713375/resttemplate-and-acessing-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!