我正在构建一个使用 Spring MVC 4.10 和 jackson 2.3.2 的应用程序。 我有一个 Project 类,它有子 Proposal 对象和 Customer 对象。这些提案对象很复杂,我想返回它们的汇总 JSON View 。 Customer 对象也会发生类似的情况。我正在尝试使用 @JsonView 注释来实现这一点。
我想问一下,在容器对象类 View 中扩展成员对象类的 View 是否是这样做的方法,或者如果不是,是否有一种我不知道的更简洁的方法来实现这一点。
上下文
在今天之前,我有一种错误的印象,即您可以使用多个 View 来注释您的 Controller ,并且生成的 JSON 表示会被相应地过滤。
@JsonView({Project.Extended.class, Proposal.Summary.class, Customer.Summary.class})
@Transactional
@RequestMapping(value="/project", method=RequestMethod.GET)
public @ResponseBody List<Project> findAll() {
return projectDAO.findAll();
}
每个类都有自己的 JsonView 注解和接口(interface) 例如:
public class Customer {
...
public interface Summary {}
public interface Normal extends Summary {}
public interface Extended extends Normal {}
}
不过,只有数组中的第一个 View 才会被考虑在内。根据https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring
Only one class or interface can be specified with the @JsonView annotation, but you can use inheritance to represent JSON View hierarchies (if a field is part of a JSON View, it will be also part of parent view). For example, this handler method will serialize fields annotated with @JsonView(View.Summary.class) and @JsonView(View.SummaryWithRecipients.class):
以及http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-jsonview 中的官方文档
To use it with an @ResponseBody controller method or controller methods that return ResponseEntity, simply add the @JsonView annotation with a class argument specifying the view class or interface to be used:
所以,我最终在容器对象的 View 中扩展了成员的 View ,就像这样
@Entity
public class Project {
...
public static interface Extended extends Normal, Proposal.Extended {}
public static interface Normal extends Summary, Customer.Normal {}
public static interface Summary {}
}
并将我的 Controller 更改为此
@JsonView(Project.Extended.class)
@Transactional
@RequestMapping(value="/project", method=RequestMethod.GET)
public @ResponseBody List<Project> findAll() {
return projectDAO.findAll();
}
这似乎可以解决问题,但我找不到有关这种情况的文档或讨论。这是 JsonViews 的预期用途还是有点骇人听闻?
提前谢谢你
-帕特里西奥·马罗内
最佳答案
我相信您已根据需要配置了 View 。问题的根源不是 Spring 的 @JsonView,而是 Jackson 的 View 实现。正如 jackson 的 view documentation 中所述:
Only single active view per serialization; but due to inheritance of Views, can combine Views via aggregation.
因此,Spring 似乎只是在继承并遵守 Jackson 2 设定的限制。
关于java - 从 Rest Controller 返回对象层次结构时如何使用 Spring MVC @JsonView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30467794/