[英]Excluding properties from the JSON (during Jackson serialization) in the Spring MVC
問題:
@RestController
方法中返回對象時,排除類屬性(例如,未經授權不得公開的字段)的@RestController
方法。
class Article {
String title;
String content;
List<Comments> comments;
int status;
}
我希望能夠根據我的三種情況輕松地返回Article
對象(這只是一個虛擬的foo欄,例如示例):
目前的想法
知道我有三個想法來解決這個問題。
想法#1
使用@JsonView
。 它可以工作,但遠非簡單易行的方法(除非我誤解了文檔)
我可以使用@JsonView
注釋所有字段, @JsonView
似乎很簡單,但在將來的開發中會變得非常復雜。
class Article {
@JsonView({ArticleView.List.class, ArticleView.Detail.class, ArticleView.Admin.class})
String title;
@JsonView({ArticleView.Detail.class, ArticleView.Admin.class})
String content;
@JsonView({ArticleView.Detail.class, ArticleView.Admin.class})
List<Comments> comments;
@JsonView({ArticleView.Admin.class})
int status;
}
確實需要每次添加新視圖時都用視圖修改新屬性。 我還需要注釋每個屬性(我想盡可能地成為POJO。
想法2
DTO-我想避免創建DTO,尤其是因為添加新字段可能意味着將其添加到所有類中(盡管這似乎是我當前的選擇)
想法3
https://github.com/monitorjbl/json-view
在我看來,它似乎還不夠成熟,無法在生產中使用它。 作者雖然很活躍。
我認為我的問題相當普遍,必須采用更簡單的方法。
您可以看一下我為此目的創建的一個小項目。 可能符合您的需求:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.