如何在序列化时创建虚拟JSON属性?

时间:2016-12-11 17:27:05

标签: java json spring-boot jackson spring-data-rest

我有这个抽象类,它为我的实体提供了一些常见的属性。以下是摘录:

@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的类,并且拥有该类型的属性确实效果很好。但我想知道使用杰克逊注释是否更简单或更简单?

1 个答案:

答案 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;
}