0

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 Answers1

0

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.

dimo414
  • 47,227
  • 18
  • 148
  • 244