简体   繁体   中英

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.

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):

  1. Include all the fields
  2. Include title, content, comments
  3. Include title and content

Current ideas

Right know I've had three ideas how to solve this issue.

Idea #1

Use @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.

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.

Idea #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)

Idea #3

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM