首页 > 解决方案 > 在 GET 请求中使用 LocalDate 作为参数的 TypeMismatch 错误

问题描述

我有一个带有 3 个属性的过滤器类来搜索可用的书籍。我有两个搜索案例:搜索书籍代码列表或按日期搜索。

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class BookFilter {

    Set<Long> bookCodes;
    LocalDate fromDate;
    LocalDate toDate;

}

这是我的控制器

    @GetMapping("/books")
    public ResponseEntity<Page<BookView>> findAvailableBooks(BookFilter bookFilter, Pageable pageable) {

        Page<Book> page = service.findAvailableBooks(bookFilter);
        Page<BookView> map = page.map(book-> modelMapper.map(book, BookView.class));

        return ResponseEntity.status(HttpStatus.OK).body(map);
    }

我正在尝试在 Postman 中发送请求,例如:

http://localhost:8887/v1/api/library/books?fromDate=01-01-2019&toDate=01-31-2019

但我陷入了 typeMismatch 错误:无法从 String 类型转换为 LocalDate。我错过了什么?

标签: javaspringspring-bootpostman

解决方案


    /* 1. Get as String */
    @GetMapping("/books")
    ResponseEntity<Page<BookView>> findAvailableBooks(@RequestParam(value = "fromDate", required = false) String fromDate, @RequestParam(value = "toDate", required = false) String toDate, Pageable pageable) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");

        LocalDate fromLocalDate = LocalDate.parse(fromDate, formatter);
        LocalDate toLocalDate = LocalDate.parse(toDate, formatter);

        // other code
    }

    /* 2. Using @DateTimeFormat  */
    @GetMapping("/books")
    ResponseEntity<Page<BookView>> findAvailableBooks(@RequestParam(value = "fromDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime fromDate, @RequestParam(value = "toDate", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)  LocalDateTime toDate, Pageable pageable) {
        // other code
    }
  1. 使用 @RequestParam 将 LocalDate 作为字符串发送,然后将其转换为所需的日期格式

  2. 在日期参数中使用所需格式的 @DateTimeFormat (iso = DateTimeFormat.ISO.DATE_TIME)

此外,之前在此主题上提出了一个非常相似的问题:

如何在 Spring 中使用 LocalDateTime RequestParam?我收到“无法将字符串转换为 LocalDateTime”


推荐阅读