在 POST/PUT 期间,所有对象的单个自定义反序列化器作为它们的 id 或嵌入的整个对象 [英] single custom deserializer for all objects as their ids or embedded whole objects during POST/PUT
本文介绍了在 POST/PUT 期间,所有对象的单个自定义反序列化器作为它们的 id 或嵌入的整个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@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
I would like to be able to send a POST with json
{ name: "name", category: 2, secondaryCategories: [3,4,5] }
来自客户端
并且能够像这样反序列化:
and be able to be deserialized like:
{ name: "name", category: {id: 2 }, secondaryCategories: [{id: 3}, {id: 4}, {id: 5}] }
如果它被发送为
{ name: "name", category: {id: 2 }, secondaryCategories: [{id: 3}, {id: 4}, {id: 5}] }
我希望它仍然像现在一样工作
I would like it to still work as now
我需要什么样的注解和自定义反序列化器?希望反序列化器可以适用于所有可能具有 id 作为属性的对象
what kind of annotation and custom deserializer I need? Hopefully the deserializer can work for all possible objects that have id as a property
谢谢!
编辑
- 查看首选 zafrost 的
@JsonCreator
答案(https://stackoverflow.com/a/46618366/986160) - 查看我的完整答案 (https://stackoverflow.com/a/46618193/986160) 以扩展
StdDeserializer
并通过ObjectMapper
使用默认反序列化
- See the preferred zafrost's
@JsonCreator
answer (https://stackoverflow.com/a/46618366/986160) - See my complete answer (https://stackoverflow.com/a/46618193/986160) for extending
StdDeserializer
and using default deserialization throughObjectMapper
推荐答案
如果可以修改实体,另一种方法是使用 @JsonCreator
工厂方法
Another approach is to use @JsonCreator
factory method if you can modify your Entity
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;
}
}
甚至这样的东西也应该可以工作
Or even something like this should also work
private class Category {
private int id;
public Category() {}
@JsonCreator
public Category(int id) {
this.id = id;
}
}
这篇关于在 POST/PUT 期间,所有对象的单个自定义反序列化器作为它们的 id 或嵌入的整个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文