[英]how to ignore null when deserializing from json string to object?
我有一個如下定義的類:
// 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但是tasks部分為null。 如果它們不存在於JSON中,我希望它們在對象中都為null。
我有一個Person類的構造函數,但我沒有初始化兩個愛好和任務部分。
非常感謝
@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)
應該做的伎倆!
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.