gpt4 book ai didi

java - JSON:尝试反序列化具有空值的对象时出现 JsonMappingException

转载 作者:IT老高 更新时间:2023-10-28 20:55:34 27 4
gpt4 key购买 nike

我尝试反序列化包含空属性并具有 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 在序列化期间忽略空值?

throw :

消息:

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

最佳答案

当不小心使用原始类型作为非原始字段的 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);

关于java - JSON:尝试反序列化具有空值的对象时出现 JsonMappingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18096589/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com