2016-12-19 34 views
0

傑克遜在現場級別上有@JsonIgnoreProperties註釋,非常棒,但有時它可能很大。有沒有像@JsonIgnoreOtherProperties?

@JsonIgnoreProperties({ "name", "phone", ... "20th item"}) 
private User user; 

我在尋找類似:

@JsonIgnoreOtherProperties("email") 
private User user; 

所以這會忽略所有字段,但電子郵件。

有沒有像@JsonIgnoreOtherProperties?

回答

0

我不認爲存在,但也有實現的幾種方法你想要什麼(比你現有的解決方案等):

1)使用@JsonViewhttp://wiki.fasterxml.com/JacksonJsonViews)。示例見What is the JSON View class in Jackson and how does it work?

2)創建一個不同的User視圖,其中包含一組最少的字段,或許是UserMinimal。這可能從一個公共接口爲您的其他User視圖繼承,以表明他們真正代表同一實體。

3)定製對象映射器並使用過濾器。一個例子見How do I exclude fields with Jackson not using annotations?

就個人而言,如果您有簡單的用例,我更喜歡第一個解決方案,如果您有更復雜的用例,我更喜歡第一個解決方案。我不喜歡第三種選擇,因爲我認爲在我的經驗中,定製對象映射器會導致容易出錯的路徑。

雖然您的註釋想法聽起來很有趣。我會考慮把它作爲一個功能請求(我認爲它會去https://github.com/FasterXML/jackson-annotations/issues)。