java - 自动将对象中的所有实体引用转换为 Jersey 中的超链接
问题描述
参加类似这样的课程:
@XmlRootElement
public class Person extends AbstractEntity<Person> {
public Integer id; // Actually in AbstractEntity
public Person parent;
public Person partner;
}
使用包含相关和类似方法的 PersonResource.class @Path
-@GET
使用具有一致“//{id}”方法的基类
这会产生类似于以下内容的 JSON:
{
"id": 1,
"parent": {
"id": 2
},
"partner": {
"id": 3
}
}
相反,我希望它看起来像这样(或类似的,这样引用的对象不会部分或全部“嵌入”):
{
"id": 1,
"parent": "/people/2",
"partner": "/people/3"
}
并且对实体和其他类是透明的。
我当前的解决方案是创建一个新注释:
@Retention(RUNTIME)
@Target(TYPE)
public @interface AssignedResource {
Class<? extends AbstractResource<? extends AbstractEntity<?>>> resource();
}
然后用这个注释每个实体类,“指向”资源类。然后,在 a 的一个实例中WriterInterceptor
:
final AbstractEntity<?> ent = (AbstractEntity<?>) context.getEntity();
...
for (final Field entFields : ent.getClass().getDeclaredFields())
try {
if (entFields.getType().isAnnotationPresent(AssignedResource.class))
context.getHeaders().add(HttpHeaders.LINK,
Link.fromPath(entFields.getType()
.getAnnotation(AssignedResource.class)
.resource()
.getAnnotation(Path.class)
.value() + "/" + ((AbstractEntity<?>) entFields.get(ent)).getId())
.rel(entFields.getName())
.build());
} catch (final IllegalArgumentException | IllegalAccessException e) {
throw new InternalServerErrorException(e);
}
通过添加一些 Link: 标题,哪种方法有效。但它很老套。
是否有更好的(#define 更好更健壮,理想情况下使用框架并且需要对每个类进行最少的更改)方式?
解决方案
推荐阅读
- macos - iTerm2 像窗口一样在 vi 中打开命令响应
- python - ktrain ImportError: DLL load failed: 找不到指定的模块
- c++ - std::map 遍历具有键索引的键
- java - 我的代码中的错误是什么,一旦我查看所有我收到消息 import androidx.appcompat.app.AppCompatActivity?图片中的错误链接
- kubernetes-helm - 使用 Prometheus operator 管理 prometheus 配置
- react-native - 如何消除安装 ignite-cli 的错误?
- c# - 如何使用反射在调用链中正确设置值类型
- silverlight - 是否可以允许在线广播用户使用 Silverlight 和 Shoutcast 选择歌曲?
- php - 添加某些功能时PHP不会向AJAX返回任何内容
- r - 使用 R 中的操纵小部件按 ID 过滤 plot_ly 图表