Pergunta

Estou tentando obter os hits de uma pesquisa no Google a partir de uma sequência da 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"));
    }

}

A seguinte exceção é lançada:

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

O que estou fazendo incorretamente? Devo definir um objeto inteiro para o retorno do JSON? Isso parece excessivo, dado que tudo o que quero fazer é obter um valor.

Para referência: o Estrutura JSON retornou.

Foi útil?

Solução

Olhando para o JSON devolvido, parece que você está pedindo o membro estimado do BoldResultsCount do objeto errado. Você está pedindo hits.estimatedResultsCount, mas precisa de hits.roSponsedata.cursor.estimatedResultsCount. Não estou super familiarizado com o GSON, mas acho que você deveria fazer algo como:

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

Outras dicas

Eu tentei isso e funcionou, usando JSON e não 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 em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top