JSON:JsonMappingException尝试反序列化具有空值的对象

我尝试反序列化包含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! 

问题 :如何避免此exception或承诺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"]) 

cause: java.lang.NullPointerException

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

 objectMapper.setSerializationInclusion(Include.NON_NULL); 

希望这能解决你的问题。

但是在反序列化期间得到的NullPointerException对我来说似乎很可疑(jackson理想情况下应该能够处理序列化输出中的null值)。 你可以发布对应于PersonResponse类的代码吗?

有时在意外使用基本类型作为非原始字段的getter的返回类型时会出现此问题:

 public class Item { private Float value; public float getValue() { return value; } public void setValue(Float value) { this.value = value; } } 

注意getValue() – 方法的“float”而不是“Float”,这可能导致Null指针exception,即使你已添加

 objectMapper.setSerializationInclusion(Include.NON_NULL); 

我也遇到了同样的问题。

我只是在模型类中包含一个默认构造函数以及带参数的其他构造函数。

有效。

 package objmodel; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; public class CarModel { private String company; private String model; private String color; private String power; public CarModel() { } public CarModel(String company, String model, String color, String power) { this.company = company; this.model = model; this.color = color; this.power = power; } @JsonDeserialize public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } @JsonDeserialize public String getModel() { return model; } public void setModel(String model) { this.model = model; } @JsonDeserialize public String getColor() { return color; } public void setColor(String color) { this.color = color; } @JsonDeserialize public String getPower() { return power; } public void setPower(String power) { this.power = power; } }