Home > Blockchain >  Unable to convert pathvariable to object
Unable to convert pathvariable to object

Time:01-12

I want to have an object as a path variable but I get the below exception when testing. How can I fix this

@Validated
@RestController
@RequestMapping("/test/api")
public class MyRestController {

    @GetMapping("/data/{id}")
    public Data getData(@PathVariable @Valid IdData id) {
        return new Data();
    }
}
@Data
public class IdData {

    private Integer id;

    public IdData(Integer id) {
        this.id = id;
    }

}

Exception:

org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'com.test.IdData'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.test.IdData': no matching editors or conversion strategy found

CodePudding user response:

From "/data/{id}" you will get an id which is an integer but the method parameter is trying to get IdData value which is incompatible.

@Validated
@RestController
@RequestMapping("/test/api")
public class MyRestController {

    @GetMapping("/data/{id}")
    public Data getData(@Valid @PathVariable int id) {
        return new Data();
    }
}

Output:-

{
   "repository": {
      "metricName": "spring.data.repository.invocations",
      "autotime": {
         "enabled": true,
         "percentilesHistogram": false,
         "percentiles": null
      }
   }
}

CodePudding user response:

you could change your @PathVariable Data Type from IdData to an Integer. Just add some logic to get the IdData by the id in path, which can be done by using JPA's findById() method. It might also be easier to pass in an integer in the path rather than an entire object.

  •  Tags:  
  • Related