我试图从查询的字符串中获取谷歌搜索的匹配。Java:错误地使用GSon? (空指针异常)
public class Utils {
public static int googleHits(String query) throws IOException {
String googleAjax = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
String json = stringOfUrl(googleAjax + query);
JsonObject hits = new Gson().fromJson(json, JsonObject.class);
return hits.get("estimatedResultCount").getAsInt();
}
public static String stringOfUrl(String addr) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
URL url = new URL(addr);
IOUtils.copy(url.openStream(), output);
return output.toString();
}
public static void main(String[] args) throws URISyntaxException, IOException {
System.out.println(googleHits("odp"));
}
}
下抛出异常:
Exception in thread "main" java.lang.NullPointerException
at odp.compling.Utils.googleHits(Utils.java:48)
at odp.compling.Utils.main(Utils.java:59)
我在做什么错误?我应该为Json返回定义一个完整的对象吗?这看起来过分了,因为我想要做的就是获得一个价值。
仅供参考:returned JSON structure。