2009-12-08 108 views
0

我試圖從查詢的字符串中獲取谷歌搜索的匹配。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,看起來您正在請求錯誤對象的estimatedResultsCount成員。您正在詢問hits.estimatedResultsCount,但您需要hits.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; 
}