差異處
這裏顯示兩個版本的差異處。
Both sides previous revision 前次修改 下次修改 | 前次修改 | ||
java:jackson:annotation:jsonautodetect [2016/02/21 17:08] tony |
java:jackson:annotation:jsonautodetect [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 5: | 行 5: | ||
* 預設的輸出欄位顯示規則 | * 預設的輸出欄位顯示規則 | ||
* 如何使用@JsonAutoDetect去改變欄位顯示規則 | * 如何使用@JsonAutoDetect去改變欄位顯示規則 | ||
+ | * Global顯示規則之設定 | ||
===== Default Visibility ===== | ===== Default Visibility ===== | ||
在沒有特別設定的情況下,Jackson的Serializer是根據Get Method與Class的public data member決定欄位名稱。 | 在沒有特別設定的情況下,Jackson的Serializer是根據Get Method與Class的public data member決定欄位名稱。 | ||
行 25: | 行 26: | ||
{"name":"test","valid":false} | {"name":"test","valid":false} | ||
</code> | </code> | ||
- | ===== Default @JsonAutoDetect ===== | + | ===== Use @JsonAutoDetect ===== |
+ | @JsonAutoDetect提供五種項目設定,其中creatorVisibility與setterVisibility的實際用途還不曉得,之後再研究: | ||
+ | * fieldVisibility: 針對data member。 | ||
+ | * getterVisibility: 針對getXXX()。 | ||
+ | * isGetterVisibility: 針對type為boolean的isXXX()。 | ||
+ | 預設情況下,成員變數必須宣告為public才會出現在結果。假如使用了fieldVisibility=Visibility.ANY,則會將private成員變數也輸出: | ||
+ | <code java> | ||
+ | @JsonAutoDetect(fieldVisibility=Visibility.ANY) | ||
+ | public static class AutoDetectObject { | ||
+ | private String mName ; | ||
+ | public AutoDetectObject(){ | ||
+ | |||
+ | } | ||
+ | private void setName(String aName){ | ||
+ | mName = aName; | ||
+ | } | ||
+ | |||
+ | public String getName(){ | ||
+ | return mName; | ||
+ | } | ||
+ | } | ||
+ | </code> | ||
+ | Output: | ||
+ | <code> | ||
+ | {"mName":"test","name":"test"} | ||
+ | </code> | ||
+ | 而getterVisibility與isGetterVisibility也類似,只是針對項目不同而已。 | ||
+ | ===== Global visibility ===== | ||
+ | 如果visibility的規則一致,且不想在各類別上設定,則可以透過調整ObjectMapper的VisibilityChecker達到目的: | ||
+ | <code java> | ||
+ | VisibilityChecker<?> checker = mapper.getVisibilityChecker(). | ||
+ | withGetterVisibility(Visibility.NONE). | ||
+ | withIsGetterVisibility(Visibility.NONE); | ||
+ | mapper.setVisibility(checker); | ||
+ | </code> | ||
+ | 如果有特別需求的部分,只要再使用@JsonAutoDetect就可以覆蓋了。 | ||
+ | ===== Summary ===== | ||
+ | 一般情況下是不太需要使用到@JsonAutoDetect或VisibilityChecker。除非每個要顯示的欄位都已透過@JsonProperty定義,且名稱可能與Get Method不同,這時候你就會需要將getterVisibility與isGetterVisibility設為NONE;當然你也可以用@JsonIgnore將Get Method濾掉。至於要用哪種,就視你喜好而定了。 | ||
===== Reference ===== | ===== Reference ===== | ||
* [[http://www.cowtowncoder.com/blog/archives/2011/02/entry_443.html|Filtering properties]] | * [[http://www.cowtowncoder.com/blog/archives/2011/02/entry_443.html|Filtering properties]] | ||
+ | * [[http://tutorials.jenkov.com/java-json/jackson-annotations.html|Jackson annotations]] | ||
+ | * [[http://stackoverflow.com/questions/7105745/how-to-specify-jackson-to-only-use-fields-preferably-globally|how to specify jackson to only use fields - preferably globally?]] | ||
===== ===== | ===== ===== | ||
---- | ---- | ||
\\ | \\ | ||
~~DISQUS~~ | ~~DISQUS~~ |