杰克逊不能用一个参数构造函数构造实例
Jackson cannot construct instance with one parameter constructor
我正在使用 Spring Boot 创建 Web 应用程序。其中一个端点期望 json 对象具有一个 属性,即 studentId
。我像其他函数一样使用 DTO 来捕获负载。
@PostMapping("/courses/{id}/students")
public SuccessResponse<Void> addEnrolls(@PathVariable Long id, @RequestBody StudentIdPayload payload) throws HandledException {
courseService.addEnrolls(id, payload.getStudentId());
return success(HttpStatus.OK);
}
@Data
@AllArgsConstructor
public class StudentIdPayload {
private Long studentId;
}
但是当我尝试 post 带有 json 正文 {"studentId":1}
的端点时,我收到以下错误:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.bimoadityar.univms.dto.input.StudentIdPayload` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
如果我 post 只使用值 1
就可以了。
如何让它与对象负载一起工作?
有趣的是,当我将另一个 属性 添加到 StudentIdPayload
时,例如 String placeholder
,它按预期工作,尽管这个解决方案感觉很老套。
考虑到 https://github.com/FasterXML/jackson-databind/issues/1498,这似乎是预期的行为。
对于我的特殊情况,我很满意将 @JsonCreator
添加到我的构造函数中。
@Data
@AllArgsConstructor(onConstructor = @__(@JsonCreator))
public class StudentIdPayload {
private Long studentId;
}
默认情况下,反序列化需要无参数构造函数,所以添加@NoArgsConstructor
:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentIdPayload {
private Long studentId;
}
另见:
我正在使用 Spring Boot 创建 Web 应用程序。其中一个端点期望 json 对象具有一个 属性,即 studentId
。我像其他函数一样使用 DTO 来捕获负载。
@PostMapping("/courses/{id}/students")
public SuccessResponse<Void> addEnrolls(@PathVariable Long id, @RequestBody StudentIdPayload payload) throws HandledException {
courseService.addEnrolls(id, payload.getStudentId());
return success(HttpStatus.OK);
}
@Data
@AllArgsConstructor
public class StudentIdPayload {
private Long studentId;
}
但是当我尝试 post 带有 json 正文 {"studentId":1}
的端点时,我收到以下错误:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.bimoadityar.univms.dto.input.StudentIdPayload` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)
如果我 post 只使用值 1
就可以了。
如何让它与对象负载一起工作?
有趣的是,当我将另一个 属性 添加到 StudentIdPayload
时,例如 String placeholder
,它按预期工作,尽管这个解决方案感觉很老套。
考虑到 https://github.com/FasterXML/jackson-databind/issues/1498,这似乎是预期的行为。
对于我的特殊情况,我很满意将 @JsonCreator
添加到我的构造函数中。
@Data
@AllArgsConstructor(onConstructor = @__(@JsonCreator))
public class StudentIdPayload {
private Long studentId;
}
默认情况下,反序列化需要无参数构造函数,所以添加@NoArgsConstructor
:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class StudentIdPayload {
private Long studentId;
}
另见: