2016-04-06 214 views
5

我知道在將對象序列化爲JSON時跳過帶空值的字段有很多問題。 當將JSON反序列化爲對象時,我想跳過/忽略具有空值的字段。使用Gson或Jackson反序列化JSON時忽略空字段

考慮類

public class User { 
    Long id = 42L; 
    String name = "John"; 
} 

和JSON字符串

{"id":1,"name":null} 

在做

User user = gson.fromJson(json, User.class) 

我想user.id是 '1',user.name是 '約翰'。

這是可能與Gson或傑克遜在一般的方式(沒有特殊的TypeAdapter或類似)?

+0

user.name將如何成爲'John'。如果示例json有「name」:null?你問是否可以跳過Json中的空值並且不覆蓋類中的默認值? –

+0

@jeffporter是的,這正是問題所在。 – FWeigl

+0

你有沒有找到一個漂亮的解決方案呢? – jayeffkay

回答

0

要跳過使用TypeAdapters,我會讓POJO在調用setter方法時執行空檢查。

還是看

@JsonInclude(value = Include.NON_NULL) 

註釋必須在一流水平,沒有方法的水平。

@JsonInclude(Include.NON_NULL) //or Include.NON_EMPTY, if that fits your use case 
public static class RequestPojo { 
    ... 
} 

對於反序列化,您可以在課程級別使用以下內容。

@JsonIgnoreProperties(ignoreUnknown =真)

+3

@JsonInclude(value = Include.NON_NULL)似乎只在序列化時才起作用,而不是在反序列化時起作用。 – FWeigl

0

我做了什麼在我的情況是設置在吸氣

public class User { 
    private Long id = 42L; 
    private String name = "John"; 

    public getName(){ 
     //You can check other conditions 
     return name == null? "John" : name; 
    } 
} 

我想這將是許多領域的一個痛苦的默認值,但它的工作原理在數量較少的字段的簡單情況下

0

雖然不是最簡潔的解決方案,但您可以使用Jackson自定義設置屬性@JsonCreator

public class User { 
    Long id = 42L; 
    String name = "John"; 

    @JsonCreator 
    static User ofNullablesAsOptionals(
      @JsonProperty("id") Long id, 
      @JsonProperty("name") String name) { 
     if (id != null) this.id = id; 
     if (name != null) this.name = name; 
    } 
} 
相關問題