簡體   English   中英

在Spring MVC中排除JSON中的屬性(在Jackson序列化期間)

[英]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. 包括所有字段
  2. 包括標題,內容,評論
  3. 包括標題和內容

目前的想法

知道我有三個想法來解決這個問題。

想法#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

在我看來,它似乎還不夠成熟,無法在生產中使用它。 作者雖然很活躍。

我認為我的問題相當普遍,必須采用更簡單的方法。

您可以看一下我為此目的創建的一個小項目。 可能符合您的需求:

https://github.com/Antibrumm/jackson-antpathfilter

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM