我正在尝试构建一个Spring MVC控制器,它将接收带有JSON格式参数的POSTed表单,并让Spring自动将其转换为Java对象.
application/x-www-form-urlencodeddata.json这是控制器:
@Controller
public class MyController {
@RequestMapping(value = "/formHandler", method = RequestMethod.POST)
public @ResponseBody String handleSubscription(
@RequestParam("data.json") MyMessage msg) {
logger.debug("id: " + msg.getId());
return "OK";
}
}
Run Code Online (Sandbox Code Playgroud)
这就是MyMessage对象的样子:
public class MyMessage {
private String id;
// Getter/setter omitted for brevity
}
Run Code Online (Sandbox Code Playgroud)
也许并不奇怪,发布带有参数data.json = {"id":"Hello"}的表单会导致HTTP错误500,并出现此异常:
org.springframework.beans.ConversionNotSupportedException:
Failed to convert value of type 'java.lang.String' to required type 'MyMessage'
nested exception is java.lang.IllegalStateException:
Cannot convert value of type [java.lang.String] to required type [MyMessage]: no matching editors …Run Code Online (Sandbox Code Playgroud)