java - Gson解析问题,空指针异常

标签 java android json gson

这是 API 中配置的 JSON 格式:

{  
"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 解析 json 的模型类

hotel_list.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;
}
}

酒店.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 并尝试解析它。

在后台执行

@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 为 null。 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/11032100/11032008/11032008_3_t.jpg\",\"URL\":\"http://media.expedia.com/hotels/12000000/11040000/11032100/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)

   

最佳答案

尝试将通用列表类型更改为简单数组:

public ArrayList<hotel> hotel_list;

至:

public hotel[] hotel_list;

Gson gson = gsonBuilder.create();

至:

Gson gson = new Gson();

关于java - Gson解析问题,空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32725464/

相关文章:

java - 通知栏覆盖应用程序。如何修复它?

java - 在 Java 中有效 Item 89 : For instance control, 更喜欢枚举类型而不是 readResolve - 为什么窃取者可以更改原始实例的字段?

Android - match_parent 忽略 layout_margin

android - 如何在运行时更改 LinearLayout 的大小?

javascript - 如何对包含 HTML 字符的 JSON 字符串进行编码?

java - 如何使用 JUnit 在 Java 中测试简单的命令行应用程序

java - 对日期字段进行排序以获得最早的日期

java - 在设备 < Android M 上找不到类 'org.simpleframework.xml.core.Persister'

javascript - Http 状态未在 try 和 catch javascript 上触发

javascript - 有没有更短的方法