Java: Utilizzo GSON in modo errato? (Eccezione puntatore nullo)
Domanda
Sto cercando di ottenere i colpi di una ricerca di Google da una stringa della query.
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"));
}
}
Il seguente eccezione viene generata:
Exception in thread "main" java.lang.NullPointerException
at odp.compling.Utils.googleHits(Utils.java:48)
at odp.compling.Utils.main(Utils.java:59)
Che cosa sto facendo in modo errato? Dovrei essere la definizione di un intero oggetto per il ritorno JSON? Che sembra eccessiva, dato che tutto quello che voglio fare è ottenere un valore.
Per riferimento: il tornato JSON struttura
.Soluzione
Guardando il JSON restituito, sembra che si sta chiedendo per il membro estimatedResultsCount dell'oggetto sbagliato. Ti stai chiedendo hits.estimatedResultsCount, ma è necessario hits.responseData.cursor.estimatedResultsCount. Io non sono super familiarità con GSON, ma penso che si dovrebbe fare qualcosa di simile:
return hits.get("responseData").get("cursor").get("estimatedResultsCount");
Altri suggerimenti
Ho provato questo e ha funzionato, utilizzando JSON e 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;
}