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 리턴의 전체 객체를 정의해야합니까? 내가하고 싶은 것은 하나의 가치를 얻는 것만으로도 과도하게 보입니다.
참조 : the 반환 된 JSON 구조.
해결책
반환 된 JSON을보고, 당신은 잘못된 객체의 추정 값 스캔 멤버를 요구하는 것 같습니다. hits.estimatedResultsCount를 요구하지만 HITS.REPONSEDATA.CURSOR.ESTIMATEDRESULTSCOUNT가 필요합니다. 나는 GSON에 매우 익숙하지 않지만 다음과 같은 일을해야한다고 생각합니다.
return hits.get("responseData").get("cursor").get("estimatedResultsCount");
다른 팁
나는 이것을 시도했고 그것은 GSON이 아닌 JSON을 사용하여 효과가있었습니다.
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