Question

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
Was it helpful?

Solution

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.

OTHER TIPS

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());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top