jackson 无法在 Spring Boot 中使用请求主体中的字段(接口)以获得多态支持

watbbzwu  于 2022-11-08  发布在  Spring
关注(0)|答案(1)|浏览(180)

我计划我的Spring项目可以处理多个请求表单,例如:

{
   "notification": "order_creation_notification",
   "data": {
       "date": "22 Jan 2022"
   }
}

{
   "notification": "login_notification",
   "data": {
       "email": "johndoe@email.com",
       "at": "LA, USA"
   }
}

因此,我创建了我的控制器和请求主体,如下所示:

  • 下面是我的控制器:
@PostMapping(value="/")
public void createNotification(@RequestBody NotificationRequest request) {
            ...
    }
  • 下面是我请求类:

第一个
但是,当我尝试使用此json主体执行POST时:

{
   "notification": "login_notification",
   "data": {
       "email": "johndoe@email.com",
       "at": "LA, USA"
   }
}

我得到一个错误,它说:

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\"])
3zwjbxry

3zwjbxry1#

您的代码几乎是正确的。
只是不要在OrderCreationNotification中使用Date date
使用字段String date,并以自定义方式将String转换为Date

相关问题