小编Jon*_*ahl的帖子

在Spring MVC 4.0中自动转换JSON表单参数

我正在尝试构建一个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";
    }
}
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)

java spring json spring-mvc jackson

9
推荐指数
2
解决办法
1万
查看次数

标签 统计

jackson ×1

java ×1

json ×1

spring ×1

spring-mvc ×1