我正在尝试构建一个Spring MVC控制器,它将接收带有JSON格式参数的POSTed表单,并让Spring自动将其转换为Java对象.
请求内容类型是 application/x-www-form-urlencoded
包含JSON字符串的参数的名称是 data.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"; } }
这就是MyMessage对象的样子:
public class MyMessage { private String id; // Getter/setter omitted for brevity }
也许并不奇怪,发布带有参数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 or conversion strategy found
如果我正确读取MappingJackson2HttpMessageConverter文档,则由Content-Type触发Jackson JSON转换application/json
,我显然无法使用,因为这是一个表单POST(我不控制POST部分).
是否有可能让Spring将JSON字符串转换为MyMessage的实例,或者我应该放弃,将其作为字符串读取并自己执行转换?