2015-09-22 34 views
0

這是JSON格式作爲API的配置:GSON解析的問題,空指針異常

{ 
"Hotels":[ 
    { 
    "EANHotelID":"257219", 
    "Country":"IN", 
    "Name":"Toshali Sands Ethnic Village Resort", 
    "LowRate":"88.32", 
    "HighRate":"118.77", 
    "Latitude":"19.83861", 
    "Longitude":"85.89400", 
    "Location":"Near the bay", 
    "PostalCode":"752002", 
    "PropertyCategory":"3", 
    "PropertyCurrency":"INR", 
    "StarRating":"4.0", 
    "StateProvince":"", 
    "CheckInTime":"10 AM", 
    "CheckOutTime":"8 AM", 
    "City":"Puri", 
    "Confidence":"52", 
    "AirportCode":"BBI", 
    "Caption":"Featured Image", 
    "ThumbnailURL":"http://media.expedia.com/hotels/2000000/1720000/1710100/1710078/1710078_35_t.jpg", 
    "URL":"http://media.expedia.com/hotels/2000000/1720000/1710100/1710078/1710078_35_b.jpg" 
    }, 
    { 
    "EANHotelID":"397792", 
    "Country":"IN", 
    "Name":"MAYFAIR Heritage, Puri", 
    "LowRate":"138.8325", 
    "HighRate":"176.55", 
    "Latitude":"19.79851", 
    "Longitude":"85.83413", 
    "Location":"Near Puri Beach", 
    "PostalCode":"752002", 
    "PropertyCategory":"1", 
    "PropertyCurrency":"INR", 
    "StarRating":"4.0", 
    "StateProvince":"", 
    "CheckInTime":"8 AM", 
    "CheckOutTime":"8 AM", 
    "City":"Puri", 
    "Confidence":"60", 
    "AirportCode":"BBI", 
    "Caption":"Featured Image", 
    "ThumbnailURL":"http://media.expedia.com/hotels/5000000/4790000/4780200/4780106/4780106_20_t.jpg", 
    "URL":"http://media.expedia.com/hotels/5000000/4790000/4780200/4780106/4780106_20_b.jpg" 
    }, 
    { 
    "EANHotelID":"397792", 
    "Country":"IN", 
    "Name":"MAYFAIR Heritage, Puri", 
    "LowRate":"138.8325", 
    "HighRate":"176.55", 
    "Latitude":"19.79851", 
    "Longitude":"85.83413", 
    "Location":"Near Puri Beach", 
    "PostalCode":"752002", 
    "PropertyCategory":"1", 
    "PropertyCurrency":"INR", 
    "StarRating":"4.0", 
    "StateProvince":"", 
    "CheckInTime":"8 AM", 
    "CheckOutTime":"8 AM", 
    "City":"Puri", 
    "Confidence":"60", 
    "AirportCode":"BBI", 
    "Caption":"Featured Image", 
    "ThumbnailURL":"http://media.expedia.com/hotels/5000000/4790000/4780200/4780106/4780106_20_t.jpg", 
    "URL":"http://media.expedia.com/hotels/5000000/4790000/4780200/4780106/4780106_20_b.jpg" 
    } 
    ] 
    } 

而這些我都用來解析使用GSON

hotel_list json的模型類的.java

public class hotel_list { 
@SerializedName("Hotels") 
@Expose 
public ArrayList<hotel> hotel_list; 

public ArrayList<hotel> getHotel_list() { return hotel_list;} 

public void setHotel_list(ArrayList<hotel> hotel_list) { 
    this.hotel_list = hotel_list; 
} 
} 

hotel.java

public class hotel { 



@SerializedName("EANHotelID") 
@Expose 

private String EANHotelID; 

@SerializedName("Country") 
@Expose 
private String Country; 

@SerializedName("Name") 
@Expose 
private String Name; 

@SerializedName("LowRate") 
@Expose 
private String LowRate; 

@SerializedName("HighRate") 
@Expose 
private String HighRate; 

@SerializedName("Latitude") 
@Expose 
private String Latitude; 

@SerializedName("Longitude") 
@Expose 
private String Longitude; 

@SerializedName("Location") 
@Expose 
private String Location; 

@SerializedName("PostalCode") 
@Expose 
private String PostalCode; 

@SerializedName("PropertyCategory") 
@Expose 
private String PropertyCategory; 

@SerializedName("PropertyCurrency") 
@Expose 
private String PropertyCurrency; 

@SerializedName("StarRating") 
@Expose 
private String StarRating; 

@SerializedName("StateProvince") 
@Expose 
private String StateProvince; 

@SerializedName("CheckInTime") 
@Expose 
private String CheckInTime; 

@SerializedName("CheckOutTime") 
@Expose 
private String CheckOutTime; 

@SerializedName("City") 
@Expose 
private String City; 

@SerializedName("Confidence") 
@Expose 
private String Confidence; 

@SerializedName("AirportCode") 
@Expose 
private String AirportCode; 

@SerializedName("Caption") 
@Expose 
private String Caption; 

@SerializedName("ThumbnailURL") 
@Expose 
private String ThumbnailURL; 

@SerializedName("URL") 
@Expose 
private String URL; 


public String getEANHotelID() { 
    return EANHotelID; 
} 

public void setEANHotelID(String EANHotelID) { 
    this.EANHotelID = EANHotelID; 
} 

public String getCountry() { 
    return Country; 
} 

public void setCountry(String country) { 
    Country = country; 
} 

public String getName() { 
    return Name; 
} 

public void setName(String name) { 
    Name = name; 
} 

public String getLowRate() { 
    return LowRate; 
} 

public void setLowRate(String lowRate) { 
    LowRate = lowRate; 
} 

public String getHighRate() { 
    return HighRate; 
} 

public void setHighRate(String highRate) { 
    HighRate = highRate; 
} 

public String getLatitude() { 
    return Latitude; 
} 

public void setLatitude(String latitude) { 
    Latitude = latitude; 
} 

public String getLongitude() { 
    return Longitude; 
} 

public void setLongitude(String longitude) { 
    Longitude = longitude; 
} 

public String getLocation() { 
    return Location; 
} 

public void setLocation(String location) { 
    Location = location; 
} 

public String getPostalCode() { 
    return PostalCode; 
} 

public void setPostalCode(String postalCode) { 
    PostalCode = postalCode; 
} 

public String getPropertyCategory() { 
    return PropertyCategory; 
} 

public void setPropertyCategory(String propertyCategory) { 
    PropertyCategory = propertyCategory; 
} 

public String getPropertyCurrency() { 
    return PropertyCurrency; 
} 

public void setPropertyCurrency(String propertyCurrency) { 
    PropertyCurrency = propertyCurrency; 
} 

public String getStarRating() { 
    return StarRating; 
} 

public void setStarRating(String starRating) { 
    StarRating = starRating; 
} 

public String getStateProvince() { 
    return StateProvince; 
} 

public void setStateProvince(String stateProvince) { 
    StateProvince = stateProvince; 
} 

public String getCheckInTime() { 
    return CheckInTime; 
} 

public void setCheckInTime(String checkInTime) { 
    CheckInTime = checkInTime; 
} 

public String getCheckOutTime() { 
    return CheckOutTime; 
} 

public void setCheckOutTime(String checkOutTime) { 
    CheckOutTime = checkOutTime; 
} 

public String getCity() { 
    return City; 
} 

public void setCity(String city) { 
    City = city; 
} 

public String getConfidence() { 
    return Confidence; 
} 

public void setConfidence(String confidence) { 
    Confidence = confidence; 
} 

public String getAirportCode() { 
    return AirportCode; 
} 

public void setAirportCode(String airportCode) { 
    AirportCode = airportCode; 
} 

public String getCaption() { 
    return Caption; 
} 

public void setCaption(String caption) { 
    Caption = caption; 
} 

public String getThumbnailURL() { 
    return ThumbnailURL; 
} 

public void setThumbnailURL(String thumbnailURL) { 
    ThumbnailURL = thumbnailURL; 
} 

public String getURL() { 
    return URL; 
} 

public void setURL(String URL) { 
    this.URL = URL; 
} 
} 

這是AsyncTask doInBackground方法,它獲取json並嘗試解析它。

doInBackground

@Override 
    protected hotel_list doInBackground(Void... params) { 

     hotel_list hotelList = new hotel_list(); 

     try { 
      //Create an HTTP client 
      HttpClient client = new DefaultHttpClient(); 
      HttpGet post = new HttpGet(url); 


      //Perform the request and check the status code 
      HttpResponse response = client.execute(post); 


      StatusLine statusLine = response.getStatusLine(); 
      Log.e(REST, Integer.toString(statusLine.getStatusCode())); 
      if (statusLine.getStatusCode() == 200) { 
       HttpEntity entity = response.getEntity(); 
       InputStream content = entity.getContent(); 




       try { 
        //Read the server response and attempt to parse it as JSON 

        BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
        // Log.e(TAG, reader.readLine()); 
        GsonBuilder gsonBuilder = new GsonBuilder(); 
        gsonBuilder.setDateFormat("M/d/yy hh:mm a"); 
        Gson gson = gsonBuilder.create(); 
        String str=reader.readLine(); 
        Log.i("json object",str); 
        hotelList = gson.fromJson(reader, hotel_list.class); 

        content.close(); 






        // handlePostsList(posts); 
       } catch (Exception ex) { 
        Log.e(REST, "Failed to parse JSON due to: " + ex); 

       } 
      } else { 
       Log.e(REST, "Server responded with status code: " + statusLine.getStatusCode()); 

      } 
     } catch (Exception ex) { 
      Log.e(REST, "Failed to send HTTP POST request due to: " + ex); 

     } 
     Log.i("list",hotelList.getHotel_list().get(1).getName()); 
     return hotelList; 
    } 

現在的問題是:返回的hotelList爲空。 GSON沒有顯示任何錯誤,但解析的內容沒有被填充到列表中,並且它仍然是空的。我究竟做錯了什麼?

logcat的消息 -

09-23 01:42:52.374 1950-1963/com.neelraj.hotels W/art﹕ Suspending all  threads took: 25.899ms 
09-23 01:42:54.321 1950-1995/com.neelraj.hotels I/json object﹕ " {\"Hotels\":[{\"EANHotelID\":\"176933\",\"Country\":\"IN\",\"Name\":\"The Park Kolkata\",\"LowRate\":\"76.13\",\"HighRate\":\"226.5\",\"Latitude\":\"22.55409\",\"Longitude\":\"88.35143\",\"Location\":\"Near New Market\",\"PostalCode\":\"700016\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"5.0\",\"StateProvince\":\"\",\"CheckInTime\":\"2 PM\",\"CheckOutTime\":\"noon\",\"City\":\"Kolkata\",\"Confidence\":\"52\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/1000000/530000/523000/522928/522928_33_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/1000000/530000/523000/522928/522928_33_b.jpg\"},{\"EANHotelID\":\"185519\",\"Country\":\"IN\",\"Name\":\"The Peerless Inn - Kolkata\",\"LowRate\":\"91.36\",\"HighRate\":\"137.04\",\"Latitude\":\"22.56217\",\"Longitude\":\"88.35157\",\"Location\":\"Near New Market\",\"PostalCode\":\"700 013\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"4.0\",\"StateProvince\":\"\",\"CheckInTime\":\"noon\",\"CheckOutTime\":\"noon\",\"City\":\"Kolkata\",\"Confidence\":\"52\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/2000000/1070000/1066400/1066383/1066383_13_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/2000000/1070000/1066400/1066383/1066383_13_b.jpg\"},{\"EANHotelID\":\"516167\",\"Country\":\"IN\",\"Name\":\"Hotel O2 VIP\",\"LowRate\":\"56.32\",\"HighRate\":\"71.55\",\"Latitude\":\"22.63360\",\"Longitude\":\"88.43468\",\"Location\":\"In Kolkata (Dum Dum)\",\"PostalCode\":\"700052\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"3.0\",\"StateProvince\":\"\",\"CheckInTime\":\"\",\"CheckOutTime\":\"noon\",\"City\":\"kolkata\",\"Confidence\":\"\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/12000000/11040000/0/11032008/11032008_3_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/12000000/11040000/0/11032008/11032008_3_b.jpg\"},{\"EANHotelID\":\"198401\",\"Country\":\"IN\",\"Name\":\"Taj Bengal\",\"LowRate\":\"192.7119\",\"HighRate\":\"859.6464\",\"Latitude\":\"22.53706\",\"Longitude\":\"88.33366\",\"Location\":\"Near Alipore Zoo\",\"PostalCode\":\"700 027\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"5.0\",\"StateProvince\":\"\",\"CheckInTime\":\"2 PM\",\"CheckOutTime\":\"Noon\",\"City\":\"Kolkata\",\"Confidence\":\"95\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/1000000/470000/465100/465007/465007_77_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/1000000/470000/465100/465007/465007_77_b.jpg\"},{\"EANHotelID\":\"215054\",\"Country\":\"IN\",\"Name\":\"ITC Sonar Kolkata\",\"LowRate\":\"174.9995\",\"HighRate\":\"221.9965\",\"Latitude\":\"22.54331\",\"Longitude\":\"88.39665\",\"Location\":\"Near Science City\",\"PostalCode\":\"700046\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"5.0\",\"StateProvince\":\"\",\"CheckInTime\":\"2 PM\",\"CheckOutTime\":\"\",\"City\":\"Kolkata\",\"Confidence\":\"52\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/1000000/930000/922100/922011/922011_66_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/1000000/930000/922100/922011/922011_66_b.jpg\"},{\"EANHotelID\":\"219474\",\"Country\":\"IN\",\"Name\":\"Golden Parkk\",\"LowRate\":\"78.57\",\"HighRate\":\"126.9\",\"Latitude\":\"22.54741\",\"Longitude\":\"88.34966\",\"Location\":\"Near Victoria Memorial\",\"PostalCode\":\"700071\",\"PropertyCategory\":\"1\",\"PropertyCurrency\":\"INR\",\"StarRating\":\"3.0\",\"StateProvince\":\"\",\"CheckInTime\":\"3 PM\",\"CheckOutTime\":\"noon\",\"City\":\"Kolkata\",\"Confidence\":\"52\",\"AirportCode\":\"CCU\",\"Caption\":\"Featured Image\",\"ThumbnailURL\":\"http://media.expedia.com/hotels/2000000/1060000/1056000/1055970/1055970_41_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/2000000/1060000/105 
    09-23 01:42:54.344 1950-1995/com.neelraj.hotels E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1 
Process: com.neelraj.hotels, PID: 1950 
java.lang.RuntimeException: An error occured while executing doInBackground() 
     at android.os.AsyncTask$3.done(AsyncTask.java:300) 
     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) 
     at java.util.concurrent.FutureTask.setException(FutureTask.java:222) 
     at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
     at java.lang.Thread.run(Thread.java:818) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList com.neelraj.hotels.model.hotel_list.getHotel_list()' on a null object reference 
     at com.neelraj.hotels.MainActivity$Fetch.doInBackground(MainActivity.java:153) 
     at com.neelraj.hotels.MainActivity$Fetch.doInBackground(MainActivity.java:84) 
     at android.os.AsyncTask$2.call(AsyncTask.java:288) 
     at java.util.concurrent.FutureTask.run(FutureTask.java:237)  
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 

+2

你可以減少這個問題的代碼量的最小數量嗎? – khelwood

+2

也,請顯示您的logcat。 –

+0

提示:如果您可以通過格式化程序運行您的單行JSON,那麼對於人們來說更容易。 Web上有JSON格式器,例如https://jsonformatter.curiousconcept.com/。 – halfer

回答

0

你是讀你的數據從你的輸入流轉換爲字符串,然後傳遞一個輸入流的JSON解析例程。它已經在文件的末尾,所以它讀取一個空的輸入,它不是對象/數組,而是返回null。您應該刪除下列lines--

String str=reader.readLine(); 
Log.i("json object",str); 

或通過在字符串中您已經閱讀 -

hotelList = gson.fromJson(str, hotel_list.class); //pass str instead of reader 

我建議沒有預先讀入一個字符串,因爲這將是更高效並處理多行文件。

1

試圖改變通用的列表類型來簡單陣列:

public ArrayList<hotel> hotel_list;

到:

public hotel[] hotel_list;

Gson gson = gsonBuilder.create();

到:

Gson gson = new Gson();

+0

更改爲一個簡單的數組不起作用。它仍然不解析 – Neel

+0

編輯我的答案 –

+0

它仍然爲空 – Neel

1

問題可能是這樣的:

hotelList = gson.fromJson(reader, hotel_list.class);

變化:

StringBuilder builder = new StringBuilder(); 
String aux = ""; 

while ((aux = reader.readLine()) != null) { 
    builder.append(aux); 
} 

hotelList = gson.fromJson(builder.toString(), hotel_list.class);