[英]Excluding properties from the JSON (during Jackson serialization) in the Spring MVC
Problem: 问题:
An easy way to exclude class properties (ex. fields that shouldn't be exposed to public without authorization) while object returned in the @RestController
method. @RestController
方法中返回对象时,排除类属性(例如,未经授权不得公开的字段)的@RestController
方法。
class Article {
String title;
String content;
List<Comments> comments;
int status;
}
I would like to be able to easily return Article
objects accordingly to the three scenarios I have (that's just a dummy foo bar like example): 我希望能够根据我的三种情况轻松地返回
Article
对象(这只是一个虚拟的foo栏,例如示例):
Current ideas 目前的想法
Right know I've had three ideas how to solve this issue. 知道我有三个想法来解决这个问题。
Idea #1 想法#1
Use @JsonView
. 使用
@JsonView
。 It works but it's far from being an easy and straightforward approach (unless I've misunderstood the documentation) 它可以工作,但远非简单易行的方法(除非我误解了文档)
I can annotate all the fields with the @JsonView
which seems easy at first but it gets really complicated in the future development. 我可以使用
@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;
}
It does require me to modify a new property with a view each time I do add a new one. 确实需要每次添加新视图时都用视图修改新属性。 I would also need to annotate every single property (I'd like to be as POJO as possible.
我还需要注释每个属性(我想尽可能地成为POJO。
Idea #2 想法2
DTO - I'd like to avoid creating DTOs especially because adding new field might mean adding it in all classes (it seems to be my current choice though) DTO-我想避免创建DTO,尤其是因为添加新字段可能意味着将其添加到所有类中(尽管这似乎是我当前的选择)
Idea #3 想法3
https://github.com/monitorjbl/json-view https://github.com/monitorjbl/json-view
It just doesn't seem to me like a mature enough to use it in the production. 在我看来,它似乎还不够成熟,无法在生产中使用它。 Author is active though.
作者虽然很活跃。
I believe that my problem is rather common and there has to be an easier approach around. 我认为我的问题相当普遍,必须采用更简单的方法。
You can take a look at one small project that I have create for this purpose. 您可以看一下我为此目的创建的一个小项目。 Probably it's matching your need:
可能符合您的需求:
https://github.com/Antibrumm/jackson-antpathfilter https://github.com/Antibrumm/jackson-antpathfilter
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.