[英]java.lang.NullPointerException error while accessing method from array
[英]NullPointerException while accessing Servlet Response from Java
我正在從Java文件中調用Java servlet。 Servlet文件具有SOP以返回JSON字符串。 現在,我希望在Java代碼中使用該字符串,然后將其解析為XML。
我的代碼如下:
URL urlS = new URL (servletURL);
URLConnection urlc;
urlc = urlS.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println("We got JSON Buddy: "+inputLine);
JSONObject js = new JSONObject(inputLine);
System.out.println("We got json object js: "+js.toString());
in.close();
問題是我的Java代碼的SOP是:
12-02 10:30:12.254: I/System.out(24169): We got JSON Buddy: {"movies": { "total": 19, "movie":[{"cover":"http://content9.flixster.com/movie/11/16/04/11160419_pro.jpg","tile":"A Very Harold & Kumar 3D Christmas","MovieDuration":"(R , 1 hr. 29 min.)","showtime":" 9:35 PM 12:00 AM ","theatre":"Rave Motion Pictures 18 + IMAX","url":"http://www.flixster.com/movie/a-very-harold-and-kumar-christmas"},{"cover":"http://content6.flixster.com/movie/11/16/12/11161272_pro.jpg","tile":"Arthur Christmas 3D","MovieDuration":"(PG , 1 hr. 37 min.)","showtime":" 12:15 PM 3:00 PM 5:35 PM ","theatre":"Rave Motion Pictures 18 + IMAX","url":"http://www.flixster.com/movie/arthur-christ
12-02 10:30:12.266: I/System.out(24169): Exception: java.lang.NullPointerException
問題是我沒有在inputLine中獲得完整的輸出,另一個問題是NullPointerException。 我不知道為什么會這樣。
您正在循環執行此操作:
while ((inputLine = in.readLine()) != null)
System.out.println("We got JSON Buddy: "+inputLine);
為了終止循環, inputLine
必須為null,因此,當您到達此處時: JSONObject js = new JSONObject(inputLine);
您將得到一個空指針異常。
看看是否更好:
URL urlS = new URL (servletURL);
URLConnection urlc;
urlc = urlS.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("We got JSON Buddy: "+inputLine);
JSONObject js = new JSONObject(inputLine);
System.out.println("We got json object js: "+js.toString());
}
in.close();
看看你在這里做什么:
while ((inputLine = in.readLine()) != null)
System.out.println("We got JSON Buddy: "+inputLine);
JSONObject js = new JSONObject(inputLine);
您一直在閱讀, 直到 inputLine
為null。 然后,您致電:
JSONObject js = new JSONObject(inputLine);
因此,您的代碼實際上是:
while ((inputLine = in.readLine()) != null)
System.out.println("We got JSON Buddy: "+inputLine);
JSONObject js = new JSONObject(null);
大概就是問題所在。 因此,問題是:您想在哪里循環?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.