【问题标题】:Cannot construct instance of `java.security.Timestamp` Error in spring RestSpring Rest 中无法构造“java.security.Timestamp”错误的实例
【发布时间】:2018-12-30 17:46:01
【问题描述】:

我有一个简单的 Rest 控制器如下:

@PostMapping(value = "/DepositBalance")
public DepositBalanceResponse DepositBalance(@Valid @RequestBody DepositBalanceRequest requestDto) throws Exception {
    return depositService.GetDepositBalance(requestDto);
}

这里是 DepositBalanceRequest 字段:

private String profileId;
private String userName;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Timestamp timestamp;

当我像这样通过 Postman 调用服务时:

{
    "profileId":"asdfasdf",
    "userName":"username",
    "timestamp":"2018-12-30 20:12:20",
}

我收到以下错误:

"Type definition error: [simple type, class java.security.Timestamp]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.security.Timestamp` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2018-12-30 20:12:20')\n at [Source: (PushbackInputStream); line: 4, column: 14] (through reference chain: com.api.v1.deposit.DepositBalanceRequest[\"timestamp\"])"

我想知道我错过了什么吗?

【问题讨论】:

  • 您可能想要使用 Java 时间版本,例如 LocalDateTimeDateTime 而不是 java.securityjavax.sql 之一。
  • `@M.Deinum 谢谢,LocalDateTime 工作
  • 在将一些遗留代码升级到 Java 16 后遇到了类似的异常。使用 java.sql.Timestamp 而不是 java.security.Timestamp 对我有用。但是,是的,升级到 Java 8+ DateTime API 是更好的选择。

标签: json spring jackson timestamp spring-rest


【解决方案1】:

感谢 M.Deinum, 需要使用 LocalDateTime 而不是 Timestamp

private String profileId;
private String userName;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime timestamp;

【讨论】:

    猜你喜欢
    • 2016-07-10
    • 2021-10-06
    • 1970-01-01
    • 2018-01-17
    • 2019-04-01
    • 2018-07-05
    • 2018-07-29
    • 2020-03-27
    • 2018-08-24
    相关资源
    最近更新 更多