2016-10-11 80 views
2

由傑克遜定義自定義bean的正確方法是空序列化?傑克遜 - 定義自定義bean的方式對於序列化是空的

我想通過Json-> POJO-> Json過濾不需要的字段。如果自定義bean對象中的所有變量都爲空,我想當序列化爲JSON時,自定義bean對象不會出現。如果裏面的任何變量不爲null,則應該出現自定義bean對象。

目前,我有一個額外的方法來分配空值給自定義bean,如果所有變量都屬於它,則爲空。我在尋找的是如果傑克遜能做到這一點。

public class JsonFileContext { 

    //...Some variables 

    @JsonInclude(JsonInclude.Include.NON_EMPTY) 
    @JsonView(Views.In.class) 
    private ContentRecognize contentRecognize; 

    //...getter/setter method 
} 

ContentRecognize類

public class ContentRecognize { 

    @JsonInclude(JsonInclude.Include.NON_NULL) 
    private String type; 

    @JsonInclude(JsonInclude.Include.NON_NULL) 
    private RecognizePattern targetId; 

    @JsonInclude(JsonInclude.Include.NON_NULL) 
    private RecognizePattern msgId; 

    //...getter/setter method 
} 

期望輸出

{ 
    "var1":"var1Content", 
    "var2":"var2Content" 
} 

{ 
    "var1":"var1Content", 
    "var2":"var2Content", 
    "contentRecognize":{ 
     "type":"typeContent" 
    } 
} 

電流輸出

{ 
    "var1":"var1Content", 
    "var2":"var2Content", 
    "contentRecognize":{} 
} 

{ 
    "var1":"var1Content", 
    "var2":"var2Content", 
    "contentRecognize":{ 
     "type":"typeContent" 
    } 
} 
+0

能否請你加入ContentRecognize的剪輯代碼'班? –

+0

@TanMaiVan代碼爲ContentRecognize類增加了 – hk6279

+0

試試這個 - http://www.jsonschema2pojo.org/將json轉換爲pojo類 –

回答

1

您可以使用@JsonIgnoreProperties@JsonIgnore註解之一。

@JsonIgnoreProperties

是用來忽略串行化和反串行化的某些性質而不管其值:

,以防止指定字段從被序列化或反序列化(即,不在JSON輸出包括;或者即使它們被包括在內也被設置):@JsonIgnoreProperties({ "internalId", "secretKey" })

要忽略JSON輸入中的任何未知屬性,無一例外:@JsonIgnoreProperties(ignoreUnknown=true)

@JsonIgnore

標記註釋,指示註解的方法或字段是 通過基於內省序列化和反序列化 功能被忽略。也就是說,它不應該被認爲是「吸氣劑」,「製造者」或「創造者」。

此外,從傑克遜1.9,如果這是一個屬性關聯的唯一註解 ,還會引起導致忽略整個 屬性:也就是說,如果制定者有這樣的註釋和 吸氣沒有註釋,getter也被有效地忽略。對於不同的訪問者使用不同的註釋仍然可能是 ;所以如果只有「getter」被忽略,其他訪問器(setter或 字段)將需要顯式註釋以防止忽略(通常爲 JsonProperty)。

在你的情況我會任:

1:

@JsonIgnoreProperties({ "contentRecognize" }) 
public class JsonFileContext { 
    [...] 
} 

2:

public class JsonFileContext { 
    //...Some variables 

    @JsonIgnore 
    private ContentRecognize contentRecognize; 

    //...getter/setter method 
} 

3:註釋contentRecognize吸氣與@JsonIgnore