gpt4 book ai didi

java - RESTEasy POJO json "embedded"对象作为链接/id

转载 作者:行者123 更新时间:2023-11-30 08:10:35 25 4
gpt4 key购买 nike

我在纠结如何将 POJO 中的嵌入对象表示为链接而不是直接嵌入它们时遇到了问题。

我正在与 Jettison 供应商一起取消 RESTEasy。全部在 3.0.11.Final 版本中。

Book.java POJO

public class Book
{
private Integer bookId;
private String title;
private Author author;
}

作者.java POJO

public class Author
{
private Integer authorId;
private String name;
}

当我使用 RESTEasy 生成一本书的 XML 或 JSON 表示时,我看到了这个:

<book>
<bookId>1</bookId>
<title>My book</title>
<author>
<authorId>2</authorId>
<name>Andre Schild</name>
</author>
</book>

但我不想这样:

<book>
<bookId>1</bookId>
<title>My book</title>
<author author="2"><atom:link rel="list" href="http://.../rest/authors/2"/></author>
</book>

由于我们使用 JPA 作为数据库后端连接,POJO 直接包含作者 POJO,而不仅仅是 ID。

我也用 Jersey 做了一些测试,但也卡在了同样的问题上

最佳答案

因为没有人知道作者字段和 URI 之间的关系,所以这不会自动发生。使用插件 reasteasy-links,您可以使用两个注释 @AddLinks@LinkResource 定义这些关系。你可以找到more information in the docs .

此插件不会更改字段的值,但会向实体添加原子链接。此外,它仅适用于 Jettison 和 JAXB。

这是一个使用 Jackson 的快速+肮脏的例子它真正取代了作者字段的值。

我们将使用这个注解来定义 POJO 和资源之间的关系:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Linked {

String path();

String rel() default "";

}

这个注解需要应用到 Author 类:

@Linked(path = "/rest/authors/{authorId}", rel = "list")
public class Author {}

在 Book 字段中,我们需要添加我们要使用的 Serializer:

public class Book {
@JsonSerialize(using = LinkedSerializer.class)
private Author author;
}

Serializer 看起来像这样:

public class LinkedSerializer extends JsonSerializer<Object> {

@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
Linked linked = value.getClass().getAnnotation(Linked.class);
Matcher matcher = Pattern.compile("\\{(.+?)\\}").matcher(linked.path());
if (!matcher.find()) {
return;
}
String param = matcher.group(1);
try {
Field field = value.getClass().getDeclaredField(param);
field.setAccessible(true);
Object paramValue = field.get(value);
String path = linked.path().replaceFirst("\\{.*\\}", paramValue.toString());
jgen.writeStartObject();
jgen.writeFieldName("href");
jgen.writeString(path);
jgen.writeFieldName("rel");
jgen.writeString(linked.rel());
jgen.writeEndObject();
} catch (NoSuchFieldException | SecurityException | IllegalAccessException ex) {
throw new IllegalArgumentException(ex);
}
}

}

注意:我们在这里只使用路径而不是完整的 URI,因为我们不知道基本 URI,也无法在此序列化程序中注入(inject) UriInfo 或 ServletRequest。但是您可以通过 ResteasyProviderFactory.getContextData(HttpServletRequest.class) 获取 ServletRequest。

关于java - RESTEasy POJO json "embedded"对象作为链接/id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31592329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com