差異處
這裏顯示兩個版本的差異處。
下次修改 | 前次修改 | ||
java:jackson:annotation:jsonignore [2016/02/21 14:15] tony 建立 |
java:jackson:annotation:jsonignore [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 46: | 行 46: | ||
</code> | </code> | ||
==== @JsonIgnore ==== | ==== @JsonIgnore ==== | ||
- | 假如我們要Ignore的變數為mEmail,可以在get method與變數宣告上使用@JsonIgnore: | + | 假如我們要Ignore的變數為mEmail,可以在get函式與變數宣告上使用@JsonIgnore: |
<code java> | <code java> | ||
@JsonProperty(value="email") | @JsonProperty(value="email") | ||
行 57: | 行 57: | ||
} | } | ||
</code> | </code> | ||
- | 假如你沒使用@JsonProperty,可以在get method宣告即可:(Jackson會把get method與使用@JsonProperty當成兩個個體) | + | 假如你沒使用@JsonProperty,可以在get函式宣告即可:(Jackson會把get method與使用@JsonProperty當成兩個個體) |
<code java> | <code java> | ||
private String mEmail; | private String mEmail; | ||
行 75: | 行 75: | ||
} | } | ||
</code> | </code> | ||
- | 但如果@JsonProperty所宣告的名稱與get method不同,@JsonIgnoreProperties必須包含兩者: | + | 但如果@JsonProperty所宣告的名稱與get函式不同,@JsonIgnoreProperties必須包含兩者: |
<code java> | <code java> | ||
@JsonIgnoreProperties({"email","mail"}) | @JsonIgnoreProperties({"email","mail"}) | ||
行 87: | 行 87: | ||
} | } | ||
</code> | </code> | ||
+ | 假如你要針對類別中某個成員內的欄位做忽略,以Map為例: | ||
+ | <code java> | ||
+ | @JsonProperty(value="metadata") | ||
+ | @JsonIgnoreProperties({"test1","test2"}) | ||
+ | private Map<String, Object> mMetadata; | ||
+ | |||
+ | public Student() { | ||
+ | mMetadata = new HashMap<String, Object>(); | ||
+ | |||
+ | Map<String, Object> tmp = new HashMap<String, Object>(); | ||
+ | tmp.put("test1", "789"); | ||
+ | tmp.put("test2", "111"); | ||
+ | tmp.put("test3", "222"); | ||
+ | |||
+ | mMetadata.put("test1", "123"); | ||
+ | mMetadata.put("test2", "456"); | ||
+ | mMetadata.put("test3", tmp); | ||
+ | } | ||
+ | </code> | ||
+ | 所宣告的物件,也會忽略包含value中的欄位: | ||
+ | <code> | ||
+ | {"passwd":"123456","id":"user","metadata":{"test3":{"test3":"222"}}} | ||
+ | </code> | ||
+ | ===== Summary ===== | ||
+ | 本篇介紹的@JsonIgnore與@JsonIgnoreProperties,可以讓產生的內容不包含你所宣告的欄位。總結以上: | ||
+ | - @JsonIgnore宣告於要Ignore的欄位上。 | ||
+ | - @JsonIgnoreProperties宣告於類別上,指定要Ignore之項目;如果宣告於成員或get函式,則是針對內容類別的欄位做忽略。 | ||
+ | - 兩者在Serialize時,就會被忽略。如果想要選擇性的顯示,必須透過Filter的方式。 | ||
+ | ===== Reference ===== | ||
+ | * [[http://www.davismol.net/2015/03/10/jackson-json-difference-between-jsonignore-and-jsonignoreproperties-annotations/|Jackson JSON: difference between @JsonIgnore and @JsonIgnoreProperties annotations]] | ||
===== ===== | ===== ===== | ||
---- | ---- | ||
\\ | \\ | ||
~~DISQUS~~ | ~~DISQUS~~ |