2014-04-09 32 views
1

這是我從URL返回的JSON字符串,我想從下面的JSON字符串中提取highDepth值。如何從JSON中嵌入的JSON中提取屬性?

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

我在這裏使用GSON,因爲我是GSON的新手。如何使用GSON從上述JSON Strirng中提取highDepth

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

// parse jsonResponse to extract highDepth 
+0

這是一個可能重複: http://stackoverflow.com/questions/8233542/parse-a-nested -json - 使用 - GSON http://stackoverflow.com/questions/19169754/parsing-nested-json-data-using-gson http://stackoverflow.com/questions/4453006/java-gson-parsing-nested-within-nested – Zoneh

回答

2

您創建一個對的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  
} 

,那麼你使用的RestTemplate#getForObject(..)通話

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

無需GSON。


沒有的POJO,因爲RestTemplate默認使用傑克遜,你可以檢索JSON樹爲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. 
+0

謝謝你的建議。但假設我在我的用例中不需要任何POJO。我只需要提取「highDepth」值 - 那麼我該怎麼做呢? – john

+0

@ user2809564看我的編輯。 –

+0

男人,你救了我的一週,我發現我可以使用com.fasterxml.jackson.databind.node.ObjectNode作爲我的POJO的一個字段,如果我不想解析它或者它是動態改變的並且應該是例如由Gson手動解析。 –

1

指的JSON parsing using Gson for Java,我就喜歡寫東西

JsonElement element = new JsonParser().parse(jsonResponse); 
JsonObject rootObject = element.getAsJsonObject(); 
JsonObject statsObject = rootObject.getAsJsonObject("stats"); 
Integer highDepth = Integer.valueOf(statsObject.get("highDepth").toString());