即使检查空值,JsonMappingException也是如此

时间:2014-10-21 05:50:15

标签: java json

我在对我传递给ObjectMapper Json Parser方法的字符串执行null和empty检查时遇到异常。这是我的代码:

private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

@RequestMapping(value = "/url", method = RequestMethod.GET)
    public ModelAndView displayStuff(
            @RequestParam(value = "item") int itemCode) throws JsonProcessingException, IOException {


           if (!text.equals("") || text != null) {
                JsonNode jsonThresholds = OBJECT_MAPPER.readTree(text);
                do stuff()..

          }else {
               do nothing();
          }
     }

我得到了这个例外:

com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
 at [Source: java.io.StringReader@182d2fd7; line: 1, column: 1]
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:164)
    at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:2840)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:2782)
    at com.fasterxml.jackson.databind.ObjectMapper.readTree(ObjectMapper.java:1659)

有人可以向我解释发生了什么以及如何解决这个问题。

三江源

1 个答案:

答案 0 :(得分:2)

更改

!text.equals("") || text != null

text != null && !text.equals("")


因为即使text="",文本!= null也会变为真,并进入if ..

你应该首先检查是否为null,因为如果value为null .equls将给nullpointer exception

这也是错误的

 !text.equals("")  &&  text != null 
       ↑
     null pointer Exception can be occurred here