我正在使用Spring Boot 2.x,Spring Data REST,Spring HATEOAS。 我有一个简单的豆子:
@Entity
public class Printer extends AbstractEntity {
@NotBlank
@Column(nullable = false)
private String name;
// Ip address or hostname
@NotBlank
@Column(nullable = false)
private String remoteAddress;
@NotNull
@Enumerated(EnumType.STRING)
@Column(nullable = false)
@JsonSerialize(using = PrinterModelSerializer.class)
private PrinterModel model;
@NotNull
@Column(nullable = false, columnDefinition = "BIT DEFAULT 0")
private boolean ssl = false;
// The store where the device is connected
@ManyToOne(fetch = FetchType.LAZY, optional = false)
private Store store;
我为枚举PrinterModel
添加了自定义序列化器:
public class PrinterModelSerializer extends JsonSerializer<PrinterModel> {
@Override
public void serialize(PrinterModel value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject(); // {
gen.writeStringField("key", value.toString());
gen.writeStringField("name", value.getName());
gen.writeBooleanField("fiscal", value.isFiscal());
gen.writeStringField("imageUrl", value.getImageUrl());
gen.writeEndObject(); // }
gen.close();
}
}
当我使用Spring Data REST存储库获取资源打印机时,我已经:
{
"sid" : "",
"createdBy" : "admin",
"createdDate" : "2018-10-16T12:29:24Z",
"lastModifiedDate" : "2018-10-16T14:12:08.671566Z",
"lastModifiedBy" : "ab48d95f-09f3-40ba-b8ba-e6fd206a2fe6",
"createdByName" : null,
"lastModifiedByName" : null,
"name" : "m30",
"remoteAddress" : "111.222.333.456",
"model" : {
"key" : "EPSON_M30",
"name" : "Epson TM-m30",
"fiscal" : false,
"imageUrl" : "https://www.epson.it/files/assets/converted/550m-550m/0/0/1/d/001d0815_pictures_hires_en_int_tm-m30_w_frontpaperloading_paper.tif.jpg"
}
}
如您所见,我没有HATEOAS链接。如果我删除自定义序列化程序,那么我会得到正确的答复:
{
"sid" : "",
"createdBy" : "admin",
"createdDate" : "2018-10-16T12:29:24Z",
"lastModifiedDate" : "2018-10-16T14:12:08.671566Z",
"lastModifiedBy" : "ab48d95f-09f3-40ba-b8ba-e6fd206a2fe6",
"createdByName" : null,
"lastModifiedByName" : null,
"name" : "m30",
"remoteAddress" : "111.222.333.456",
"model" : "EPSON_M30",
"ssl" : true,
"_links" : {
"self" : {
"href" : "http://x.x.x.x:8082/api/v1/printers/3"
},
"printer" : {
"href" : "http://x.x.x.x:8082/api/v1/printers/3{?projection}",
"templated" : true
},
"store" : {
"href" : "http://x.x.x.x:8082/api/v1/printers/3/store{?projection}",
"templated" : true
}
}
}
如何防止@JsonSerialize
断开HATEOAS链接?