InvalidDefinitionException:“class”的对象 ID 定义无效:找不到名称为“id”的属性

问题描述 投票:0回答:1

我有 2 个 Java 类,如下所示:

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
Class A {
   private B b;
   ...
   some more fields
   ...
   public B getB() {...}
   public void setB(B b){...}
}

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
Class B {
   private A a;
   ...
   some more fields
   ...
   public A getA() {...}
   public void setA(A a){...}
}

尝试反序列化对象 A,我收到此错误:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException:

A
的对象 ID 定义无效:找不到名称为“id”的属性

我认为在类级别使用注释会将 id 属性添加到 Json 中。这是对的吗? 怎么解决?

java serialization deserialization
1个回答
0
投票

使用generator = ObjectIdGenerators.PropertyGenerator.class表示您想要使用字段或getter方法作为“标识符”。

使用 property = "id" 表明您希望将字段 id 用作“标识符”,根据 javadoc,这是重复的,因为“id”是未写入 annation 属性字段时的默认值。

所以你可以只写@JsonIdentityInfo(ObjectIdGenerators.PropertyGenerator.class)

现在,关于您的错误,您必须在班级中提供 id 字段。注释不会创建代码,它只是代码上的元数据(如果您想到 lombok,忘记它,它是愚蠢的库)。

Jackson 通过内省在运行时处理注释,以便它知道如何使用您的类(它使用 PropertyGenerator,默认字段名称为“id”)

© www.soinside.com 2019 - 2024. All rights reserved.