@Entity public Product { @Id public int id;
public String name; @ManyToOne(cascade = {CascadeType.DETACH} ) Category category @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.DETACH} ) Set<Category> secondaryCategories; }
和这个实体:
@Entity public Category { @Id public int id; public String name; }
我希望能够使用JSON发送POST
{ name: "name", category: 2, secondaryCategories: [3,4,5] } 从客户端
{ name: "name", category: 2, secondaryCategories: [3,4,5] }
并可以像这样反序列化:
{ name: "name", category: {id: 2 }, secondaryCategories: [{id: 3}, {id: 4}, {id: 5}] }
如果它被发送为
我希望它能像现在一样工作
我需要什么样的注释和自定义反序列化器?希望反序列化程序可以对以id为属性的所有可能对象起作用
谢谢!
@JsonCreator如果您可以修改实体,则另一种方法是使用工厂方法
@JsonCreator
private class Product { @JsonProperty("category") private Category category; @JsonProperty("secondaryCategories") private List<Category> secondaryCategories; } private class Category { @JsonProperty("id") private int id; @JsonCreator public static Category factory(int id){ Category p = new Category(); p.id = id; // or some db call return p; } }
甚至像这样的事情也应该起作用
private class Category { private int id; public Category() {} @JsonCreator public Category(int id) { this.id = id; } }