e.getCategory() != null ? e.getCategory().getName() : "";
This throws a 开发者_如何学GoNullPointerException
and I do not understand why. Can anyone explain?
Explanation:
According to Java's precedence rules, your code was being parsed like this:
(("\"category\":" + "\"" + e.getCategory()) != null) ? e.getCategory().getName() : ""
with the entire concatenation (("..." + e.getCategory())
!= null
) as the condition.
Since "..." + e.getCategory()
is never null
, the code didn't work.
e
is null
.
Is e
null?
Perhaps you should try this:
(e != null) ?
(e.getCategory() != null) ?
e.getCategory().getName() :
""
: ""
Or rather, a simplified form:
(e != null && e.getCategory() != null) ?
e.getCategory().getName() :
""
Solution found....
CORRECT
bufo.append("\"category\":" + "\"" + ((e.getCategory() != null) ? e.getCategory().getName() : "") + "\",");
PROBLEM
bufo.append("\"category\":" + "\"" + e.getCategory()!=null?e.getCategory().getName():"" + "\",");
精彩评论