Unable to convert pathvariable to object
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
Solution 1:
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
}
}
}