Search code examples
springweb-servicesrestspring-restcontroller

spring rest web service @requestparam to method custom class (NOT string)


I'm using this tutorial https://spring.io/guides/gs/rest-service/

I want to pass to web service API method parameter other then String:

@RestController
public class ApiClass {

   @RequestMapping("/service")
   public int service(@RequestParam(value="paramIn") CustomClass paramIn) {
      if (paramIn.value != 0) return 1;
      else return 0;
  }

}

But when I try it I get this error:

HTTP Status 500 - Failed to convert value of type 'java.lang.String' to required type 'CustomClass'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [CustomClass]: no matching editors or conversion strategy found`

Thnaks,


Solution

  • Usual way to do this is to use POST or PUT method and annotate the the custom object with @RequestBody. For example:

     @RequestMapping(value = "/service", 
                     method = RequestMethod.POST, 
                     consumes = MediaType.APPLICATION_JSON_VALUE)
     public int service(@RequestBody CustomClass paramIn) {
    
         // do something with the paramIn
    
     }
    

    If you POST a JSON representation of your CustomClass instance to endpoint /service Spring will deserialize it and pass it as an argument to your controller.