问题
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:
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.
来源:https://stackoverflow.com/questions/35883297/gson-throwing-null-pointer-exception-when-a-field-is-missing-in-json