首页 > 解决方案 > 自动将对象中的所有实体引用转换为 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 更好更健壮,理想情况下使用框架并且需要对每个类进行最少的更改)方式?

标签: javajerseyjax-rsmoxy

解决方案


推荐阅读