【发布时间】:2014-10-03 15:02:52
【问题描述】:
场景:
- 这是一个使用普通 JavaEE 7 的 REST API
- 有一个
Person实体 -
GET /persons返回所有人的列表 -
GET /persons/{id}返回一个人
现在我希望这些 API 端点返回实体的不同表示:
-
/persons应该只返回id,firstName,lastName -
/persons/{id}应该返回所有字段
我已经想到的:
DTO 方法:创建一个只有
id、firstName和lastName字段的PersonSummary类。然后使用推土机(或其他映射器)从Person -> PersonSummary复制字段。然后返回PersonSummary对象列表。使用
javax.json.Json:手动组装返回的对象。但这样我只能得到 JSON,没有更多的 XML:(-
XML 模式文件:(不知道这是否真的可行)为每个表示编写一个
李>.xsd文件并让 Jaxb 处理生成的表示。
到目前为止我所看到的:
在 Spring 中,您可以简单地创建一个包含所有 getter 的
interface,这应该包括在内。 (就像这里(https://spring.io/blog/2014/05/21/what-s-new-in-spring-data-dijkstra)在底部)。对于 Jackson,您可以使用
@JsonView(http://wiki.fasterxml.com/JacksonJsonViews)。使用 MOXy 有
@XmlNamedObjectGraphs(https://stackoverflow.com/a/19526044/1321564)。
有没有一种(简单的)方法可以用 JavaEE 做到这一点?或者有一些不错的外部库吗?
编辑:运行时注释操作
你怎么看这个想法(这基本上就像杰克逊的@JsonView):
@XmlRootElement
public class MyClass {
@MyViewAnnotation @MyOtherViewAnnotation
String s1;
String s2;
@MyViewAnnotation
String s3;
}
怎么办? (伪代码)
// resource object comes from some JAX-RS interceptor along
// with the preferred view annotation (in this case @MyViewAnnotation)
Annotation viewAnnotation = @MyViewAnnotation;
for(Field f : resource) {
if(f.hasAnnotation(viewAnnotation)) {
f.addAnnotation(@XmlElement);
} else {
f.addAnnotation(@XmlTransient);
}
}
// return manipulated resource object back to JAX-RS
预期结果:
传递
@MyViewAnnotation时,会生成@XmlElement String s1和@XmlElement String s2。s3将是@XmlTransient。传递
@MyOtherViewAnnotation时,会在s1上生成@XmlElement。s2和s3将是@XmlTransient。
我不知道是否可以在正确的位置拦截 JAX-RS 处理以创建修改后的类,然后将该类传递给正常的 JAX-RS 处理。但这样一来,就可以轻松完成,而且 JAX-RS 可以以同样的方式生成 JSON 和 XML。
有什么想法吗?
【问题讨论】:
标签: jakarta-ee jaxb jax-rs projection jaxb2