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

筅森魡賤 提交于 2019-12-25 04:41:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!