如何从JSON中嵌入的JSON中提取属性?

时间:2014-04-09 06:03:33

标签: java json gson

这是我从URL返回的JSON字符串,我想从下面的JSON字符串中提取highDepth值。

{
  "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

2 个答案:

答案 0 :(得分: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默认使用Jackson,您可以将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.

答案 1 :(得分: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());