1

This is the JSON String I am getting back from a URL and I would like to extract highDepth value from the below JSON String.

{
  "description": "",
  "bean": "com.hello.world",
  "stats": {
    "highDepth": 0,
    "lowDepth": 0
  }
}

I am using GSON here as I am new to GSON. How do I extract highDepth from the above JSON Strirng using GSON?

String jsonResponse = restTemplate.getForObject(url, String.class);

// parse jsonResponse to extract highDepth
john
  • 11,311
  • 40
  • 131
  • 251
  • This is a possible duplicate of: http://stackoverflow.com/questions/8233542/parse-a-nested-json-using-gson http://stackoverflow.com/questions/19169754/parsing-nested-json-data-using-gson http://stackoverflow.com/questions/4453006/java-gson-parsing-nested-within-nested – Zoneh Apr 09 '14 at 06:07

2 Answers2

2

You create a pair of POJOs

public class ResponsePojo {    
    private String description;
    private String bean;
    private Stats stats;  
    //getters and setters       
}

public class Stats {    
    private int highDepth;
    private int lowDepth;
    //getters and setters     
}

You then use that in the RestTemplate#getForObject(..) call

ResponsePojo pojo = restTemplate.getForObject(url, ResponsePojo.class);
int highDepth = pojo.getStats().getHighDepth();

No need for Gson.


Without POJOs, since RestTemplate by default uses Jackson, you can retrieve the JSON tree as an ObjectNode.

ObjectNode objectNode = restTemplate.getForObject(url, ObjectNode.class);
JsonNode highDepth = objectNode.get("stats").get("highDepth");
System.out.println(highDepth.asInt()); // if you're certain of the JSON you're getting.
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Thanks for suggestion. But suppose if I don't need any POJO in my use case. I just need to extract only that `highDepth` value - How would I do that then? – john Apr 09 '14 at 06:09
  • Man, you saved my week, I figured out that I can use com.fasterxml.jackson.databind.node.ObjectNode as a field of my POJO if I don't want to parse it or if it is dynamicly changes and should be parsed manually by Gson for example. – Vadim Kirilchuk Jun 03 '15 at 20:09
1

Refering to JSON parsing using Gson for Java, I would write something like

JsonElement element = new JsonParser().parse(jsonResponse);
JsonObject rootObject = element.getAsJsonObject();
JsonObject statsObject = rootObject.getAsJsonObject("stats");
Integer highDepth = Integer.valueOf(statsObject.get("highDepth").toString());
Community
  • 1
  • 1
Smutje
  • 17,733
  • 4
  • 24
  • 41