如何使用 Spring Data Rest 在自定义序列化程序中创建超媒体链接
How do I create hypermedia links in custom serializer with Spring Data Rest
我有一个抽象 class 和两个实现:
public abstract class Attribute {
// some properties
}
public class CustomAttribute extends Attribute{
private String property1;
}
public class DefaultAttribute extends Attribute{
private String property2;
}
还有一个 class,其中包括以下属性:
public class Step{
private List<Attribute> attributes;
}
现在当 Step
被序列化时,self link 丢失了。我需要自我参考,因为我想更新属性。根据文档,jackson 需要一些帮助来决定使用哪个 class。但这无济于事,因为我需要同时使用两个 classes。因此,我为 Step
构建了一个自定义序列化程序(并在模块中注册),现在我想知道如何自己构建 link。我在 Spring Data Rest 文档中找不到与此相关的任何内容。由于 Spring Data Rest 会自动添加这些 link,我认为可能有一种方法可以让 protocol/hostname/port 信息在 JsonSerializer
中可用。如何在我的自定义序列化程序中获取信息?
好的,现在我使用 linkTo()
函数获取主机名和端口,并在我的自定义序列化程序中手动设置其余资源 URL。
final Link attributeLink = linkTo(CustomAttributeRepository.class)
.slash("/api")
.slash("customAttributes")
.slash(attribute.getIdentifier()).withSelfRel();
//@formatter:off
jsonGenerator.writeFieldName("_links");
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("self");
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("href", attributeLink.getHref());
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
//@formatter:on
我有一个抽象 class 和两个实现:
public abstract class Attribute {
// some properties
}
public class CustomAttribute extends Attribute{
private String property1;
}
public class DefaultAttribute extends Attribute{
private String property2;
}
还有一个 class,其中包括以下属性:
public class Step{
private List<Attribute> attributes;
}
现在当 Step
被序列化时,self link 丢失了。我需要自我参考,因为我想更新属性。根据文档,jackson 需要一些帮助来决定使用哪个 class。但这无济于事,因为我需要同时使用两个 classes。因此,我为 Step
构建了一个自定义序列化程序(并在模块中注册),现在我想知道如何自己构建 link。我在 Spring Data Rest 文档中找不到与此相关的任何内容。由于 Spring Data Rest 会自动添加这些 link,我认为可能有一种方法可以让 protocol/hostname/port 信息在 JsonSerializer
中可用。如何在我的自定义序列化程序中获取信息?
好的,现在我使用 linkTo()
函数获取主机名和端口,并在我的自定义序列化程序中手动设置其余资源 URL。
final Link attributeLink = linkTo(CustomAttributeRepository.class)
.slash("/api")
.slash("customAttributes")
.slash(attribute.getIdentifier()).withSelfRel();
//@formatter:off
jsonGenerator.writeFieldName("_links");
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName("self");
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("href", attributeLink.getHref());
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
//@formatter:on