【发布时间】: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])
注意:code 是 Department 的密钥。 Department id 和Serial id 构成Employee 的密钥。
【问题讨论】:
-
在你的员工类中忽略
@JsonIgnore Department department; -
只需将
department类型更改为Employee类中的整数 -
@deadshot 和 @MichalRosa - 感谢您的回复。我无法在
Employee类中将department类型更改为整数。Department仅在先前已在 JSON 中引用时表示为整数。请参阅this 了解更多信息。因此,您的建议可能适用于我提供的示例响应,但不适用于一般情况。
标签: java json spring jackson lombok