Spring Boot Failed to convert value of type ‘xxx‘ to required type ‘xxx‘问题解决

淩亂°似流年 2023-01-15 02:12 254阅读 0赞

问题描述:

org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type ‘java.lang.String’ to required type ‘java.lang.Long’;

问题分析:

1、使用Swagger调试地址栏传参的接口时,参数类型paramType设置为query,导致调用接口报错。

  1. @DeleteMapping("delete/{id}")
  2. @ApiOperation(value = "删除")
  3. @ApiImplicitParams({
  4. @ApiImplicitParam(name = "id", value = "ID", paramType = "query", dataType = "Long", required = true)
  5. })
  6. public String delete(@PathVariable("id") Long id){
  7. return "";
  8. }

解决办法:将paramType设置为path,代表地址栏传参。

  1. @DeleteMapping("delete/{id}")
  2. @ApiOperation(value = "删除")
  3. @ApiImplicitParams({
  4. @ApiImplicitParam(name = "id", value = "ID", paramType = "path", dataType = "Long", required = true)
  5. })
  6. public String delete(@PathVariable("id") Long id){
  7. return "";
  8. }

2、后端接口参数类型为Date,但是前端传参类型为String。

  1. public String testDate(@RequestParam Date time) {
  2. return DateUtil.format(time,"yyyy-MM-dd");
  3. }

解决办法:

(1)后端接口参数类型改为String,前端传参不变。

  1. public String testDate(@RequestParam String time) {
  2. return time;
  3. }

(2)后端接口参数类型添加@DateTimeFormat,将固定格式的字符串转成Date,前端传参不变。

  1. public String testDate(@RequestParam @org.springframework.format.annotation.DateTimeFormat(pattern = "yyyy-MM-dd") Date time) {
  2. return DateUtil.format(time,"yyyy-MM-dd");
  3. }

发表评论

表情:
评论列表 (有 0 条评论,254人围观)

还没有评论,来说两句吧...

相关阅读