从 json 字符串反序列到对象时如何忽略 null?

Ter*_*rry 6 java serialization json deserialization

我有一个类定义如下:

// Ignore all the unknown properties in input JSON
@JsonIgnoreProperties(ignoreUnknown = true)

// Only include non null values in deserialized Java object.
@JsonInclude(value = Include.NON_NULL)
public class Person {


@JsonProperty("person_id")
private String personId;

@JsonProperty("school")
private String school;

@JsonProperty("hobbies")
private Map<String, List<AttributeBag>> hobbies = new   HashMap<String, List<AttributeBag>>();

@JsonProperty("tasks")
private Map<String, Map<String, AttributeBag>> tasks = new HashMap<String, Map<String, AttributeBag>>();



 public Map<String, List<AttributeBag>> getHobbies() {
    return hobbies;
}


   public Person(String person_id, String school) {
    super();
    this.person_id = person_id;
    this.school = school;

}
Run Code Online (Sandbox Code Playgroud)

当我使用下面的 JSON 字符串将字符串反序列化为对象时,

 {
"person_id":"123",
"school":"stanford University"
}
Run Code Online (Sandbox Code Playgroud)

从我反序列化的对象中,爱好已创建但为空,甚至任务也未创建。我期待像“任务”这样的方式,如果 JSON 中没有相应的字段,它不应该在对象中反序列化。

但奇怪的是:当我检查 object.getHobbies()!=null 但任务部分为 null 时。如果 JSON 中不存在,我希望对象中的两者都为 null。

我有一个 Person 类的构造函数,但我没有初始化爱好和任务部分。

多谢

dev*_*v2d 3

@JsonProperty("hobbies")
private Map<String, List<AttributeBag>> hobbies = new   HashMap<String, List<AttributeBag>>();

@JsonProperty("tasks")
private Map<String, Map<String, AttributeBag>> tasks = new HashMap<String, Map<String, AttributeBag>>();
Run Code Online (Sandbox Code Playgroud)

从上面的代码可以清楚地看出,无论如何,您正在为爱好和任务创建新对象,我无法理解为什么您的任务没有创建(它应该创建为空地图)

并回答你的问题@JsonInclude(value = Include.NON_NULL)应该可以解决问题!