Java 使用Jackson序列化两个具有相同id的不同POJO对象
我有两门课:Java 使用Jackson序列化两个具有相同id的不同POJO对象,java,json,serialization,jackson,deserialization,Java,Json,Serialization,Jackson,Deserialization,我有两门课: @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id",scope = Rol.class) public class Rol extends MyEntity implements Serializable { private Integer id; private String rolName; public Rol(Intege
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id",scope = Rol.class)
public class Rol extends MyEntity implements Serializable {
private Integer id;
private String rolName;
public Rol(Integer id, String rolName) {
this.id = id;
this.rolName = rolName;
}
...
}
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id",scope = User.class)
public class User extends MyEntity implements Serializable {
private Integer id;
private String name;
private List<Rol> rolList;
public User(Integer id, String name, List<Rol> rolList) {
this.id = id;
this.name = name;
this.rolList = rolList;
}
...
}
结果应该是什么时候
{"id": 1,"name": "MyName","rolList": [{"id": 1,"rolName": "MyRol"},1]}
因为rol1和rol2是id为1的相同POJO标识符的不同实例
如何避免JsonMappingException?在我的项目中,我有一些相同POJO的不同实例。我可以保证如果id相等->对象相等
请原谅我英语不好。在这种情况下,Jackson希望不同的类实例有不同的
id
。在github之前已经有过讨论。重写hashCode
和等于将无济于事。对象引用必须匹配相等的id
选择权
重用Rol
实例,而不是创建具有相同字段的新实例。作为奖励,您还可以节省内存
修改应用程序逻辑,使其不依赖于@JsonIdentityInfo
对于任何回到这个问题的人来说,在Jackson中似乎有一个自定义ObjectdResolver选项来实现这一点。您可以在@JsonIdentityInfo注释中指定此项,例如:
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class,property=“name”,
解析程序=CustomObjectedResolver.class)
然后,或许可以包装普通的SimpleObjectdResolver类,开始定制bindItem()
在我的例子中,我希望避免对象重叠,因此在我开始新的东西时清除了引用:
公共类CustomObjectdResolver实现ObjectdResolver{
私有objectdresolver objectdresolver;
公共CustomObjectedResolver(){
clearReferences();
}
@凌驾
公共void bindItem(IdKey id,对象pojo){
//是时候放弃推荐信了?
if(某物的pojo实例)
clearReferences();
ObjectDresolver.bindItem(id,pojo);
}
@凌驾
公共对象解析id(IdKey id){
返回ObjectDresolver.resolveId(id);
}
@凌驾
公共布尔canUseFor(ObjectdResolver resolverType){
返回resolverType.getClass()==getClass();
}
@凌驾
公共对象解算器newForDeserialization(对象上下文){
返回新的CustomObjectedResolver();
}
私有void clearReferences(){
ObjectDresolver=新的SimpleObjectDresolver();
}
}
{"id": 1,"name": "MyName","rolList": [{"id": 1,"rolName": "MyRol"},{"id": 1,"rolName": "MyRol"}]}
{"id": 1,"name": "MyName","rolList": [{"id": 1,"rolName": "MyRol"},1]}