VB_*_*VB_ 20 java json jackson json-deserialization
我尝试反序列化包含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!
Run Code Online (Sandbox Code Playgroud)
但是:如果扔掉"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!
Run Code Online (Sandbox Code Playgroud)
问题:如何避免此异常或承诺杰克逊在序列化期间忽略空值?
抛出:
信息:
com.fasterxml.jackson.databind.MessageJsonException:
com.fasterxml.jackson.databind.JsonMappingException:
N/A (through reference chain: person.Create["person"]->Person["firstName"])
Run Code Online (Sandbox Code Playgroud)
原因:
com.fasterxml.jackson.databind.MessageJsonException:
com.fasterxml.jackson.databind.JsonMappingException:
N/A (through reference chain: prson.Create["person"]->Person["firstName"])
Run Code Online (Sandbox Code Playgroud)
原因: java.lang.NullPointerException
Nem*_*man 49
有时在意外使用基本类型作为非原始字段的getter的返回类型时会出现此问题:
public class Item
{
private Float value;
public float getValue()
{
return value;
}
public void setValue(Float value)
{
this.value = value;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意getValue() - 方法的"float"而不是"Float",这可能会导致Null指针异常,即使您已添加
objectMapper.setSerializationInclusion(Include.NON_NULL);
Run Code Online (Sandbox Code Playgroud)
Jac*_*all 19
如果您不想序列化null值,可以使用以下设置(在序列化期间):
objectMapper.setSerializationInclusion(Include.NON_NULL);
Run Code Online (Sandbox Code Playgroud)
希望这能解决你的问题.
但是NullPointerException你在反序列化过程中得到的结果对我来说似乎很可疑(杰克逊理想情况下应该能够处理null序列化输出中的值).你能发布与PersonResponse班级相对应的代码吗?
| 归档时间: |
|
| 查看次数: |
69058 次 |
| 最近记录: |