2009-12-08 5 views
0

Я пытаюсь получить хиты поиска google из строки запроса.Java: Неправильно используется GSon? (исключение нулевого указателя)

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? Это кажется чрезмерным, учитывая, что все, что я хочу сделать, это получить одно значение.

Для справки: returned JSON structure.

ответ

1

Глядя на возвращенный JSON, кажется, что вы просите оцененного членаResultsCount не того объекта. Вы запрашиваете hits.estimatedResultsCount, но вам нужны hit.responseData.cursor.estimatedResultsCount. Я не супер знакомы с Gson, но я думаю, что вы должны сделать что-то вроде:

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

Я попытался это и он работал, используя JSON и не 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; 
} 
Смежные вопросы