【发布时间】:2015-03-03 22:28:50
【问题描述】:
我有一个类定义如下:
// 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;
}
当我使用下面的 JSON 字符串从字符串反序列化为对象时,
{
"person_id":"123",
"school":"stanford University"
}
从我反序列化的对象来看,爱好是创建但为空,甚至任务都没有创建。我期待像“任务”这样的方式,如果 JSON 中没有相应的字段,它不应该在对象中反序列化。
但奇怪的是:当我检查 object.getHobbies()!=null 但任务部分为空时。如果 JSON 中不存在它们,我希望它们在对象中都为 null。
我有一个 Person 类的构造函数,但我没有初始化爱好和任务部分。
非常感谢
【问题讨论】:
-
发布您的构造函数代码可能会很有用。根据您所拥有的,
hobbies和tasks都应该是非空的空地图 -
@MrWiggles 构造函数已更新。为什么他们都应该是非空的。我期望的是,如果它们不在 JSON 中,我不希望它们在对象中反序列化。该怎么做?
标签: java json serialization deserialization