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.
Gson is correctly returning a
null
value forgetReviews()
since there aren't any reviews in the JSON. It is yourprintln()
call that is causing the NPE, because you cannot call.get(0)
onnull
.Add a null-check before your
println()
, e.g.Alternatively have your
getReviews()
method return a non-nullList
whenreviews
isnull
.