当json中缺少一个字段时,GSON会抛出空指针异常 [英] GSON throwing null pointer exception when a field is missing in json
问题描述
ReviewClass:
GSON在json中缺少字段时抛出空指针异常 public class ReviewClass
{
private String name;
私人列表< Review>审查;
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复习{
私人字符串名称;
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}
所以,当json中没有reviews字段时,GSON会抛出空指针异常。请帮助我。 p>
println()
调用,因为你不能在 null
上调用 .get(0)
。在 println()
之前添加空检查,例如
if (reviewResults.getReviews()!= null){
>
System.out.println(reviewResults.getReviews()。get(0).getName());
}
或者,您的
getReviews()
方法返回一个非空当
reviews $时列出
c $ c>是null
。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.if (reviewResults.getReviews() != null) { System.out.println(reviewResults.getReviews().get(0).getName()); }
Alternatively have your
getReviews()
method return a non-nullList
whenreviews
isnull
.这篇关于当json中缺少一个字段时,GSON会抛出空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!