【问题标题】:How to deserialize in Jackson JSON created using @JsonIdentityInfo如何在使用@JsonIdentityInfo 创建的杰克逊 JSON 中反序列化
【发布时间】:2020-12-18 03:17:00
【问题描述】:

鉴于以下 JSON:

{
  "id": 1,
  "code": "HR",
  "employees": [
    {
      "id": 1,
      "department": 1,
      "serial": {
        "id": 254,
        "type": {
          "code": "XYZ",
          "active": true
        }
      }
    }]
}

我如何让 Jackson 将其反序列化为以下类?我试过这个:

@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIdentityInfo(scope=Department.class, generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "id")
public class Department {
   int id;
   String code;
   List<Employee> employees
}


@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIdentityInfo(scope=Employee.class, generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "id")
public class Employee {
   int id;
   Department department;  
   Serial serial;

}

但我收到以下错误:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: No Object Id found for an instance of `com.example.domain.Employee`, to assign to property 'id'; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: No Object Id found for an instance of `com.example.domain.Employee`, to assign to property 'id'
     at [Source: (PushbackInputStream); line: 1, column: 713] (through reference chain: com.example.domain.Department["employees"]->java.util.ArrayList[0])

注意:codeDepartment 的密钥。 Department id 和Serial id 构成Employee 的密钥。

【问题讨论】:

  • 在你的员工类中忽略@JsonIgnore Department department;
  • 只需将department 类型更改为Employee 类中的整数
  • @deadshot 和 @MichalRosa - 感谢您的回复。我无法在 Employee 类中将 department 类型更改为整数。 Department 仅在先前已在 JSON 中引用时表示为整数。请参阅this 了解更多信息。因此,您的建议可能适用于我提供的示例响应,但不适用于一般情况。

标签: java json spring jackson lombok


【解决方案1】:

首先,您在 List&lt;Employee&gt; employees 中缺少分号 :))

另外,我相信这些类都在独立的 .java 文件中,因为它们都是公共的。但没有它,你甚至不应该能够编译你的代码:)) 所以我假设你已经涵盖了这两件事。

我也认为 Employee 类中的部门可能存在问题 - 在您的类中,它是 Department 类型,但在您的 JSON 中,它是 int 类型。

尝试将属性部门的 Employee 类中的类型从 Department 切换为 int - 我还建议将其重命名为“departmentId”或类似的名称。

【讨论】:

    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多