Spring calls your @RequestMapping methods with reflection. To resolve each argument that he will pass to the call, he uses the HandlerMethodArgumentResolver implementation. For @RequestParam annotated parameters, RequestParamMethodArgumentResolver used. This implementation binds the request parameter to a single object, usually a String or some type of Number .
However, your use case is slightly less common. You rarely get json as the request parameter , so I think you should think about your design , but if you have no other choice, you need to register a custom PropertyEditor , which will take care of converting the value of the json request parameter to its own type.
Registration is simple in the annotated @InitBinder method in your @Controller class
@InitBinder public void initBinder(WebDataBinder dataBinder) { dataBinder.registerCustomEditor(MyMessage.class, new PropertyEditorSupport() { Object value; @Override public Object getValue() { return value; } @Override public void setAsText(String text) throws IllegalArgumentException { value = new Gson().fromJson((String) text, MyMessage.class); } }); }
In this particular case, we do not need all the methods of the PropertyEditor interface, so we can use PropertyEditorSupport , which is a useful default implementation of PropertyEditor . We simply implement two methods that we take care of using the taste of the JSON parser that we want. I used Gson because it was available.
When Spring sees that it has the requested query parameter, it checks the parameter type, finds the MyMessage type MyMessage and looks for the registered PropertyEditor for this type. He will find it because we registered it, and he will use it to convert the value.
You may need to implement other PropertyEditor methods, depending on what you do next.
My recommendation is never to send JSON as a request parameter. Set the request content type to application/json and send json as the request body. Then use @RequestBody to analyze it.
Sotirios delimanolis
source share