RestTemplate and acessing json

11,021

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.

Share:
11,021
Milind
Author by

Milind

Updated on June 04, 2022

Comments

  • Milind
    Milind almost 2 years

    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