【问题标题】:Unable to pass LocalDate as JSON parameter无法将 LocalDate 作为 JSON 参数传递
【发布时间】:2022-01-26 16:13:02
【问题描述】:

我无法将 LocalDate 对象传递给我的控制器方法。邮递员告诉我有一个 JSON 解析错误。

这是我试图通过以下方式获取的实体字段:

private LocalDate transactionDate;

我的存储库方法

    List<Transactions> findAllByTransactionDateLike(LocalDate transactionDate);

我的控制器方法:

  @GetMapping
    public List<Transactions> fetchBankStatementByMonth(@RequestBody LocalDate transactionDate) {
        return transactionService.findAllByTransactionDateLike(transactionDate);
    }

我的邮递员身体:

{
    "transactionDate":"2021-12"
}

错误:

"JSON parse error: Cannot deserialize value of type `java.time.LocalDate` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `java.time.LocalDate` from Object value (token `JsonToken.START_OBJECT`)\n at [Source: (PushbackInputStream); line: 1, column: 1]"

【问题讨论】:

  • @RequestBody@PostMapping 一起使用

标签: json jpa spring-data-jpa json-deserialization


【解决方案1】:

对于@GetMapping,试试

@GetMapping
public List<Transactions> fetchBankStatementByMonth(
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) 
    LocalDate transactionDate) {
        

并在查询参数中发送请求

例如 http://localhost:8080/your-endpoint?transactionDate=2021-12-27


如果输入只包含年和月,@RequestParam 最好用java.time.YearMonth 表示

@GetMapping
public List<Transactions> fetchBankStatementByMonth(
    java.time.YearMonth transactionYearMonth) {

然后转换为 LocalDate 到您选择的日期

例如该月的第一天:

LocalDate transactionDate = LocalDate.of(transactionYearMonth.getYear(), transactionYearMonth.getMonthValue(), 1);


您似乎想按月(而不是特定日期)进行搜索 您可能需要更改您的服务方法 变成findAllByTransactionDateBetween(startDate, endDate)

并将输入的 YearMonth 值转换为每月的第一天和每月的最后一天,然后调用您的新/更新的服务方法

//1st day of month
LocalDate startDate = LocalDate.of(transactionYearMonth.getYear(), transactionYearMonth.getMonthValue(), 1);

//last day of month
LocalDate endDate = LocalDate.of(transactionYearMonth.getYear(), transactionYearMonth.getMonthValue(), transactionYearMonth.lengthOfMonth());

return transactionService.findAllByTransactionDateBetween(startDate, endDate);

【讨论】:

  • 很好,它有效,谢谢!我是否可以在不指定日期的情况下按月搜索?
  • 也许尝试单独发送 2 个参数?年,另一个月?
  • @melintteofil 添加了一个使用YearMonth的替代选项
  • YearMonth 遗憾地返回空,我的数据库有值,但 Postman 中显示的列表是空的
  • 我应该也将实体字段更改为 YearMonth,对吧?
猜你喜欢
  • 2021-10-06
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 2021-05-25
相关资源
最近更新 更多