Java: Неправильно используете GSON? (исключение нулевого указателя)
Вопрос
Я пытаюсь получить хиты поиска 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, кажется, что вы запрашиваете участника ResatedResultsCount неправильного объекта. Вы спрашиваете хиты. Я не очень знаком с GSON, но я думаю, что вы должны сделать что -то вроде:
return hits.get("responseData").get("cursor").get("estimatedResultsCount");
Другие советы
I tried this and it worked, using JSON and not 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;
}
Не связан с StackOverflow