【问题标题】:Java: Using GSon incorrectly? (null pointer exception)Java:错误地使用 Gson? (空指针异常)
【发布时间】:2009-12-08 02:19:28
【问题描述】:

我正在尝试从查询字符串中获取谷歌搜索的点击率。

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。

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    查看返回的 JSON,您似乎在请求错误对象的estimatedResultsCount 成员。您要求 hits.estimatedResultsCount,但您需要 hits.responseData.cursor.estimatedResultsCount。我对 Gson 不是很熟悉,但我认为你应该这样做:

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

    【讨论】:

      【解决方案2】:

      我试过了,它使用 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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多