Question

Je suis en train d'obtenir les succès d'une recherche Google à partir d'une chaîne de la requête.

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

}

L'exception suivante est levée:

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

Qu'est-ce que je fais mal? Dois-je définir un objet entier pour le retour JSON? Cela semble excessif, étant donné que tout ce que je veux faire est d'obtenir une valeur.

Pour référence: retour la structure JSON

.
Était-ce utile?

La solution

Recherche JSON retour, il semble que vous demandez le membre estimatedResultsCount du mauvais objet. Vous vous demandez hits.estimatedResultsCount, mais vous devez hits.responseData.cursor.estimatedResultsCount. Je ne suis pas super familier avec Gson, mais je pense que vous devriez faire quelque chose comme:

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

Autres conseils

J'ai essayé et cela a fonctionné, en utilisant JSON et non 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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top