当来自不同实体类型的ID重叠时,是否可以使用ObjectIdGenerators.PropertyGenerator来使用@JsonIdentityInfo?

xwo*_*ker 4 java xml jackson

当来自不同实体类型的ID重叠时,是否可以使用ObjectIdGenerators.PropertyGenerator来使用@JsonIdentityInfo?

假设我有以下XML并希望用Jackson 2.x反序列化它:

<foo>
  <id>3</id>
  <name>Peter</name>
  <bar>
     <id>3</id>
     <kind>dog</kind>
     <!--belongsTo>3</belongsTo-->
  </bar>
</foo>
Run Code Online (Sandbox Code Playgroud)

我已经注释了Foo和Bar类@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id").

反序列化失败了com.fasterxml.jackson.databind.JsonMappingException: Already had POJO for id (java.lang.String) [3].

如果bar有id 4,一切正常.

关于杰克逊反序列化的XML中的ID有哪些要求?我假设 - 因为Jackson知道哪个实体范围能够使用相同的id,只要它属于不同的类型.

PS:似乎设置或不设置belongsTo引用(指向foo对象).

小智 9

你可能已经找到了答案,但万一你没有......

您应该能够使用@JsonIdentityInfo 的scope参数,即,

@JsonIdentityInfo(scope=Foo.class, property="id", generator=ObjectIdGenerators.PropertyGenerator.class)
public class Foo { ... }
Run Code Online (Sandbox Code Playgroud)

@JsonIdentityInfo(scope=Bar.class, property="id", generator=ObjectIdGenerators.PropertyGenerator.class)
public class Bar { ... }
Run Code Online (Sandbox Code Playgroud)