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

2022-09-01 15:00:33

我尝试反序列化包含空属性并具有.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!

:如何避免此异常或承诺 Jackson 在序列化过程中忽略空值?

抛出:

消息:

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


答案 1

有时,当意外使用基元类型作为非基元字段的 getter 的返回类型时,会出现此问题:

public class Item
{
    private Float value;

    public float getValue()
    {
        return value;
    }

    public void setValue(Float value)
    {
        this.value = value;
    }   
}

请注意 getValue()-方法的“float”而不是“Float”,这可能会导致空指针异常,即使您添加了

objectMapper.setSerializationInclusion(Include.NON_NULL);

答案 2

如果不想序列化值,可以使用以下设置(在序列化过程中):null

objectMapper.setSerializationInclusion(Include.NON_NULL);

希望这能解决您的问题。

但是你在反序列化过程中得到的对我来说似乎很可疑(理想情况下,Jackson应该能够处理序列化输出中的值)。你能发布与类相对应的代码吗?NullPointerExceptionnullPersonResponse