[英]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.