Pregunta

Estoy intentando conseguir los éxitos de una búsqueda en Google de una cadena de la consulta.

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"));
    }

}

La excepción siguiente:

Exception in thread "main" java.lang.NullPointerException
    at odp.compling.Utils.googleHits(Utils.java:48)
    at odp.compling.Utils.main(Utils.java:59)

¿Qué estoy haciendo mal? Debería ser la definición de todo un objeto de la devolución JSON? Eso parece excesiva, dado que todo lo que quiero hacer es obtener un valor.

Para referencia: la vuelto JSON estructura

.
¿Fue útil?

Solución

Mirando el JSON devuelto, parece que usted está pidiendo el miembro estimatedResultsCount del objeto equivocado. Que está pidiendo hits.estimatedResultsCount, pero hay que hits.responseData.cursor.estimatedResultsCount. No estoy muy familiarizado con Gson, pero creo que deberías hacer algo como:

return hits.get("responseData").get("cursor").get("estimatedResultsCount");

Otros consejos

He intentado esto y funcionó, usando JSON y no 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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top