Reputation: 11699
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
Upvotes: 1
Views: 3008
Reputation: 279990
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.
Upvotes: 2
Reputation: 18153
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());
Upvotes: 1