جافا: باستخدام GSN بشكل غير صحيح؟ (استثناء مؤشر فارغ)

StackOverflow https://stackoverflow.com/questions/1864197

  •  16-09-2019
  •  | 
  •  

سؤال

أحاول الحصول على عدد من البحث في 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 الذي تم إرجاعه، يبدو أنك تطلب من عضو التقدير في الكائن الخطأ. أنت تسأل عن 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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top