Java:不正确地使用GSon?(空指针异常)
我试图从一串查询中获得谷歌搜索的点击率Java:不正确地使用GSon?(空指针异常),java,json,gson,Java,Json,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
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,似乎您要求的是错误对象的estimatedResultsCount成员。您正在请求hits.estimatedResultsCount,但需要hits.responseData.cursor.estimatedResultsCount。我对Gson不太熟悉,但我认为你应该做如下事情:
return hits.get("responseData").get("cursor").get("estimatedResultsCount");
我尝试了这个方法,它成功了,使用的是JSON而不是GSON
public static int googleHits(String query) throws IOException,
JSONException {
String googleAjax = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
URL searchURL = new URL(googleAjax + query);
URLConnection yc = searchURL.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String jin = in.readLine();
System.out.println(jin);
JSONObject jso = new JSONObject(jin);
JSONObject responseData = (JSONObject) jso.get("responseData");
JSONObject cursor = (JSONObject) responseData.get("cursor");
int count = cursor.getInt("estimatedResultCount");
return count;
}