[英]Cannot use field (interface) in request body in spring boot for polymorphism support
I plan that my spring project can handle multiple request forms like:我计划我的 spring 项目可以处理多个请求 forms ,例如:
{
"notification": "order_creation_notification",
"data": {
"date": "22 Jan 2022"
}
}
and和
{
"notification": "login_notification",
"data": {
"email": "johndoe@email.com",
"at": "LA, USA"
}
}
So, i create my controller and request body like this:所以,我创建了我的 controller 并请求这样的正文:
@PostMapping(value="/")
public void createNotification(@RequestBody NotificationRequest request) {
...
}
@JsonTypeInfo(use = Id.DEDUCTION)
@JsonSubTypes({
@Type(OrderCreationNotification.class),
@Type(LoginNotification.class)
})
public interface IData {
}
@AllArgsConstructor
@Getter
@Setter
public class OrderCreationNotification implements IData {
private Date date;
}
@AllArgsConstructor
@Getter
@Setter
public class LoginNotification implements IData {
private String email;
private String at;
}
@AllArgsConstructor
@Getter
@Setter
public class NotificationRequest {
private String notification;
private IData data;
}
But, when i try to do POST using this json body:但是,当我尝试使用此 json 主体进行 POST 时:
{
"notification": "login_notification",
"data": {
"email": "johndoe@email.com",
"at": "LA, USA"
}
}
i get an error which says:我收到一条错误消息:
JSON parse error: Cannot construct instance of `LoginNotification` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `LoginNotification` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 8, column: 13] (through reference chain: NotificationRequest[\"data\"])
Your code is almost correct.您的代码几乎是正确的。
Just don't use Date date
in OrderCreationNotification
.只是不要在OrderCreationNotification
中使用Date date
。
use field String date
, and convert String
to Date
in custom way.使用字段String date
,并以自定义方式将String
转换为Date
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.