To jest ciąg JSON, który otrzymuję z adresu URL i chciałbym go wyodrębnić highDepth
wartość z poniższego ciągu JSON.
{
"description": "",
"bean": "com.hello.world",
"stats": {
"highDepth": 0,
"lowDepth": 0
}
}
Używam GSON tutaj, ponieważ jestem nowy w GSON. Jak wyodrębnić highDepth
z powyższego JSON Strirng za pomocą GSON?
String jsonResponse = restTemplate.getForObject(url, String.class);
// parse jsonResponse to extract highDepth
Odpowiedzi:
2 dla odpowiedzi № 1Tworzysz parę POJO
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
}
Następnie użyj tego w RestTemplate#getForObject(..)
połączenie
ResponsePojo pojo = restTemplate.getForObject(url, ResponsePojo.class);
int highDepth = pojo.getStats().getHighDepth();
Nie potrzebujesz Gsona.
Odtąd bez POJO RestTemplate
domyślnie używa Jacksona, możesz pobrać drzewo JSON jako 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.
1 dla odpowiedzi nr 2
Odnosić się do Analiza JSON przy użyciu Gson for Java, Napisałbym coś takiego
JsonElement element = new JsonParser().parse(jsonResponse);
JsonObject rootObject = element.getAsJsonObject();
JsonObject statsObject = rootObject.getAsJsonObject("stats");
Integer highDepth = Integer.valueOf(statsObject.get("highDepth").toString());