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を見ると、あなたが間違ったオブジェクトのestimatedResultsCountメンバーのために求めているようです。あなたはhits.estimatedResultsCountのために求めているが、あなたはhits.responseData.cursor.estimatedResultsCountを必要としています。私はGsonとスーパー慣れていないんだけど、私はあなたのような何かを行うべきだと思います:
return hits.get("responseData").get("cursor").get("estimatedResultsCount");
他のヒント
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;
}
所属していません StackOverflow