JSON:JsonMappingException,同时尝试反序列化具有空值的对象 [英] JSON: JsonMappingException while try to deserialize object with null values
问题描述
我尝试反序列化包含空属性并具有 JsonMappingException
的对象.
I try to deserialize object that contains null-properties and have the 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"
属性 - 一切正常!我的意思是传递下一个字符串:
BUT: if to throw away "firstName = null"
property - all works fine!
I mean pass the next string:
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 在序列化期间忽略空值?
Question: How to avoid this exception or to pledge Jackson ignore null-values during serialization?
投掷:
信息:
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
推荐答案
如果不想序列化 null
值,可以使用以下设置(序列化期间):
If you don't want to serialize null
values, you can use the following setting (during serialization):
objectMapper.setSerializationInclusion(Include.NON_NULL);
希望这能解决您的问题.
Hope this solves your problem.
但是您在反序列化期间获得的 NullPointerException
对我来说似乎很可疑(Jackson 理想情况下应该能够处理序列化输出中的 null
值).能贴一下PersonResponse
类对应的代码吗?
But the NullPointerException
you get during deserialization seems suspicious to me (Jackson should ideally be able to handle null
values in the serialized output). Could you post the code corresponding to the PersonResponse
class?
这篇关于JSON:JsonMappingException,同时尝试反序列化具有空值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!