当json中缺少字段时,GSON抛出空指针异常

时间:2016-03-09 05:04:26

标签: java json gson pojo

当json中缺少某个字段时,GSON会抛出空指针异常

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;
}

}

主要代码:

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

JSON(无评论栏目):

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

所以,当没有&#34;评论&#34;时,GSON抛出空指针异常。在json的领域。请帮助我。

1 个答案:

答案 0 :(得分:0)

Gson正在为null正确返回getReviews()值,因为JSON中没有任何评论。这是导致NPE的println()来电,因为您无法在.get(0)上致电null

println()之前添加空检查,例如

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

或者,当getReviews()List时,您的reviews方法会返回非空null