GSON throwing null pointer exception when a field

2019-09-17 20:39发布

This question already has an answer here:

GSON throwing null pointer exception when a field is missing in json

ReviewClass:

public class ReviewClass
{
private String name;

private List<Review> reviews;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public List<Review> getReviews() {
    return reviews;
}

public void setReviews(List<Review> reviews) {
    this.reviews = reviews;
}
}

class Review {
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

Main code:

ReviewClass reviewResults = gson.fromJson(reader, ReviewClass.class);
System.out.println(reviewResults.getReviews().get(0).getName());

JSON(no review field):

 {"itemId":978998,"name":"Palet","salePrice":15.88,"upc":"708431191570","categoryPath":"Toys}

So, the GSON throwing null pointer exception when there is no "reviews" field in json. PLEASE HELP ME.

1条回答
家丑人穷心不美
2楼-- · 2019-09-17 21:14

Gson is correctly returning a null value for getReviews() since there aren't any reviews in the JSON. It is your println() call that is causing the NPE, because you cannot call .get(0) on null.

Add a null-check before your println(), e.g.

if (reviewResults.getReviews() != null) {
  System.out.println(reviewResults.getReviews().get(0).getName());
}

Alternatively have your getReviews() method return a non-null List when reviews is null.

查看更多
登录 后发表回答