单个自定义序列化程序,用于所有嵌入的带注释的对象,用它们的id替换它们

时间:2017-10-07 12:17:53

标签: java json serialization jackson spring-data

我有类似的实体:

@Entity
public Product {
   @Id
   public int id;

   public String name;

   @ManyToOne(cascade = {CascadeType.DETACH} )
   Category category

   @ManyToMany(cascade = {CascadeType.DETACH} )
   Set<Category> secondaryCategories;


}

@Entity
public Category {
   @Id
   public int id;

   public String name;

    @JsonCreator
    public Category(int id) {
        this.id = id;
    }

    public Category() {}
}

是否可以使用注释来注释Category类或categorysecondaryCategories属性,这些注释会将它们序列化为嵌入时的ID。

现在当我为id = 1的产品进行GET时,我从服务器上获取:

{ 
  id: 1,
  name: "product 1", 
  category: {id: 2, name: "category 2" }, 
  secondaryCategories: [{id: 3, name: "category 3" }, 
                        {id: 4, name: "category 4" }, 
                        {id: 5, name: "category 5" }] 
}

是否有可能回来:

{ 
  id: 1,
  name: "product 1", 
  category: 2, 
  secondaryCategories: [3, 4, 5]
}

使用Category注释@JsonIdentityReference(alwaysAsId = true)课程 通常工作,但当我提取一个或一个类别列表时,也只返回ids。只有在嵌入了类别时才需要ID转换。

谢谢!

1 个答案:

答案 0 :(得分:0)

您只需在类别变量上使用@JsonIdentityReference(alwaysAsId = true)

E.g:

@Entity
public Product {
   @Id
   public int id;

   public String name;

   @ManyToOne(cascade = {CascadeType.DETACH} )
   @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope=Category.class)
   @JsonIdentityReference(alwaysAsId = true)
   Category category;

   @ManyToMany(cascade = {CascadeType.DETACH} )
   Set<Category> secondaryCategories;


}