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

时间:2015-03-03 22:28:50

标签: java json serialization 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;

}

当我使用下面的JSON字符串从字符串反序列化时,

 {
"person_id":"123",
"school":"stanford University"
}

从我反序列化的对象中,业余爱好是创建但是空的,甚至没有创建任务。我期待像&#34; tasks&#34;这样的方式,如果JSON中没有相应的字段,它不应该在对象中反序列化。

但奇怪的是:当我检查object.getHobbies()!= null但是tasks部分为null。如果它们不存在于JSON中,我希望它们在对象中都为null。

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

非常感谢

2 个答案:

答案 0 :(得分:1)

@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>>();

从上面的代码中可以看出,无论如何,你都在为业余爱好和任务创建新的对象,我无法理解为什么你的任务没有被创建(它应该被创建为一个空的地图)

并回答你的问题@JsonInclude(value = Include.NON_NULL)应该做的伎俩!

答案 1 :(得分:1)

JSON反序列化器不会尝试设置不会出现在JSON结构中的字段,但这些行:

@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>>();

正在创建对象构造的值。

如果您希望它们为null,则不要在对象中分配它们,只需留下声明:

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

@JsonProperty("tasks")
private Map<String, Map<String, AttributeBag>> tasks;
相关问题