我正在尝试从查询字符串中获取Google搜索的命中。

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结构.

有帮助吗?

解决方案

看返回的JSON,看来您正在要求使用错误对象的估计resultScount成员。您正在要求hits.EstimatedResultScount,但是您需要hits.responsedata.cursor.stimatimatedResultscount。我对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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top