8

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

Milind
  • 531
  • 2
  • 12
  • 24
  • 1
    Your approach looks good. Note that just do restTemplate.getForObject(targetUrl, JsonNode.class) assuming that your restTemplate is configured to work with Jackson. – Alexey Gavrilov Jul 12 '14 at 13:49
  • "restTemplate is configured to work with Jackson" Can you please clarify this? – Milind Jul 12 '14 at 22:25
  • You can set an HttpMessageCoverter for your rest template which will covert JSON to java objects. Take a look at the example code this question: http://stackoverflow.com/questions/21355450/spring-resttemplate-with-jackson-as-httpmessageconverter-and-joda-datetime-prope – Alexey Gavrilov Jul 12 '14 at 22:39
  • Isnt that is there when you create RestTemplate Object?. I saw it has list of converters already set – Milind Jul 14 '14 at 14:24
  • 1
    Using `ObjectMapper` is redundant here. As Alexey said you can just use `com.fasterxml.jackson.databind.JsonNode` as the second argument for the `restTemplate.getForObject()` method. – androberz Dec 23 '15 at 19:39

1 Answers1

5

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.

Somu
  • 3,593
  • 6
  • 34
  • 44