一尘不染

JSON:JsonMappingException,同时尝试使用空值反序列化对象

json

我尝试反序列化包含null属性并具有的对象JsonMappingException

我做的事:

String actual = "{\"@class\" : \"PersonResponse\"," +
                "  \"id\" : \"PersonResponse\"," +
                "  \"result\" : \"Ok\"," +
                "  \"message\" : \"Send new person object to the client\"," +
                "  \"person\" : {" +
                "    \"id\" : 51," +
                "    \"firstName\" : null}}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(new StringReader(json), PersonResponse.class); //EXCEPTION!

但是 :如果扔掉"firstName = null"财产-一切正常!我的意思是传递下一个字符串:

String test = "{\"@class\" : \"PersonResponse\"," +
                "  \"id\" : \"PersonResponse\"," +
                "  \"result\" : \"Ok\"," +
                "  \"message\" : \"Send new person object to the client\"," +
                "  \"person\" : {" +
                "    \"id\" : 51}}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(new StringReader(json), PersonResponse.class); //ALL WORKS FINE!

问题 :如何避免此异常或保证杰克逊在序列化期间忽略空值?

抛出:

信息:

com.fasterxml.jackson.databind.MessageJsonException:
 com.fasterxml.jackson.databind.JsonMappingException:
  N/A (through reference chain: person.Create["person"]->Person["firstName"])

原因:

com.fasterxml.jackson.databind.MessageJsonException:
 com.fasterxml.jackson.databind.JsonMappingException:
  N/A (through reference chain: prson.Create["person"]->Person["firstName"])

原因: java.lang.NullPointerException


阅读 518

收藏
2020-07-27

共1个答案

一尘不染

如果您不想序列化null值,则可以使用以下设置(序列化期间):

objectMapper.setSerializationInclusion(Include.NON_NULL);

希望这能解决您的问题。

但是NullPointerException反序列化过程中获得的结果对我来说似乎很可疑(理想情况下,杰克逊应该能够处理null序列化输出中的值)。您可以张贴与PersonResponse课程相对应的代码吗?

2020-07-27