我有这个抽象类,它为我的实体提供了一些常见的属性。以下是摘录:
@MappedSuperclass
public class AbstractEntity implements Serializable {
@Id
@GeneratedValue
private long id;
@Temporal(value = TemporalType.TIMESTAMP)
@JsonProperty(access = Access.READ_ONLY)
private Date createdOn;
@Temporal(value = TemporalType.TIMESTAMP)
@JsonProperty(access = Access.READ_ONLY)
private Date modifiedOn;
⋮
}
将子类序列化为JSON时,我得到了预期的结果,例如,这是序列化的摘录:
{
"createdOn": "2016-12-11T15:35:23Z",
"modifiedOn": "2016-12-11T15:35:23Z",
⋮
}
我需要将这些公共属性序列化为JSON对象,以便上面的示例如下所示:
{
"_metadata": {
"createdOn": "2016-12-11T15:35:23Z",
"modifiedOn": "2016-12-11T15:35:23Z",
}
⋮
}
我已经尝试过使用名为Metadata
的类,并且拥有该类型的属性确实效果很好。但我想知道使用杰克逊注释是否更简单或更简单?
答案 0 :(得分:0)
您可以创建JPA @Embeddable
类,您应该获得所需的输出。不确定什么比这简单。
嵌入式:
@Embeddable
public class MetaData{
@Temporal(value = TemporalType.TIMESTAMP)
@JsonProperty(access = Access.READ_ONLY)
private Date createdOn;
@Temporal(value = TemporalType.TIMESTAMP)
@JsonProperty(access = Access.READ_ONLY)
private Date modifiedOn;
}
实体:
@MappedSuperclass
public class AbstractEntity implements Serializable {
@Id
@GeneratedValue
private long id;
@Embedded
private Metadata metdata;
}