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 返回定义整个对象吗?这似乎有些过分了,因为我只想得到一个值。
供参考:返回的 JSON 结构。
I'm trying to get the hits of a google search from a string of the query.
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"));
}
}
The following exception is thrown:
Exception in thread "main" java.lang.NullPointerException
at odp.compling.Utils.googleHits(Utils.java:48)
at odp.compling.Utils.main(Utils.java:59)
What am I doing incorrectly? Should I be defining an entire object for the Json return? That seems excessive, given that all I want to do is get one value.
For reference: the returned JSON structure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看返回的 JSON,您似乎正在请求错误对象的estimatedResultsCount 成员。您要求hits.estimatedResultsCount,但您需要hits.responseData.cursor.estimatedResultsCount。我对 Gson 不太熟悉,但我认为你应该这样做:
Looking the returned JSON, it seems that you're asking for the estimatedResultsCount member of the wrong object. You're asking for hits.estimatedResultsCount, but you need hits.responseData.cursor.estimatedResultsCount. I'm not super familiar with Gson, but I think you should do something like:
我尝试了这个,它有效,使用 JSON 而不是 GSON。
I tried this and it worked, using JSON and not GSON.