我有一个看起来像这样的Pojo课
@Table(name = "attachments")
public class Attachment {
@Column(name="id")
private Integer id;
@Column(name = "uuid")
private String uuid;
@Column(name = "customer_id")
private Integer customerId;
@Column(name = "size")
private Integer size;
@Column(name = "uploaded_to_minio")
private Boolean uploaded;
@Column(name = "created_at")
private LocalDateTime created;
@Column(name = "updated_at")
private LocalDateTime updated;
@Column(name = "name")
private String name;
@JsonAppend(
attrs = {
@JsonAppend.Attr(value = "DownloadLink")
}
)
public static class DownloadLink {}
// Getters, Setters omitted
}
当我调用REST端点时,例如:localhost:8080 / attachments / 2500我得到了这样的Json。 (2500是此上下文中的客户ID,端点返回List <>)
{
"id": 7,
"uuid": "8980560a-f9af-4ce5-80a6-9da384f8f886",
"customerId": 2500,
"size": 336430,
"uploaded": false,
"created": {
"hour": 11,
"minute": 24,
"second": 8,
"nano": 0,
"dayOfYear": 311,
"dayOfWeek": "WEDNESDAY",
"month": "NOVEMBER",
"dayOfMonth": 7,
"year": 2018,
"monthValue": 11,
"chronology": {
"calendarType": "iso8601",
"id": "ISO"
}
},
"updated": null,
"name": "image_2500_20130916_11_41_17.jpeg"
}
// other json omitted
它成功返回Attachment
的列表<>。现在,我想做的是在调用个人ID时将字段“ downloadLink”添加为JsonAppend
,例如localhost:8080 / attachments / 2500/7
{
"id": 7,
"uuid": "8980560a-f9af-4ce5-80a6-9da384f8f886",
"customerId": 2500,
"size": 336430,
"uploaded": false,
"created": [
2018,
11,
7,
11,
24,
8
],
"updated": null,
"name": "image_2500_20130916_11_41_17.jpeg",
"DownloadLink": "http://127.0.0.1:9000/test/8980560a-f9af-4ce5-80a6-9da384f8f886/image_2500_20130916_11_41_17.jpeg?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=EZXTCHKE2YHUNRPI8JCL%2F20181108%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20181108T101712Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=f45023cda340afcb9ba49343c0cf1a5bbb1577e8fcdb52ef59f7c2f25f967874"
}
我可以通过如下方法来实现:
@GET
@Path("customers/{customerId}/{id}")
@Produces(MediaType.APPLICATION_JSON)
public String getAttachmentById(@PathParam("customerId") Integer customerId, @PathParam("id") Integer id) throws Exception {
Attachment attachment = attachmentService.getAttachment(customerId, id);
String downloadlink = minioFileServer.getDownloadLinkForFile("test", attachment.getUuid(), attachment.getName());
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.addMixIn(Attachment.class, Attachment.DownloadLink.class);
ObjectWriter writer = mapper.writerFor(Attachment.class).withAttribute("DownloadLink", downloadlink);
String jsonString = writer.writeValueAsString(attachment);
return jsonString;
}
我真正想做的是返回一个Attachment实例本身而不是String。当我尝试这样做时:
attachment = mapper.readValue(jsonString, Attachment.class);
return attachment;
它给了我纯洁的Json,而没有像第一个json那样的downloadlink。当我返回String时,它满足了我的需求,但是当我返回Pojo时,它没有显示downloadlink。谁能帮我指出正确的方向吗?非常感谢您的帮助。