转换到JSON对象模型,同时使用@JsonProperty
问题描述:
JSON的一个模型对象的转换失败时@JsonProperty注解用于如下失败:转换到JSON对象模型,同时使用@JsonProperty
Controller类片段:
@RequestMapping(value = "/show", method = RequestMethod.POST)
public String doControl(@ModelAttribute User user, HttpServletRequest request){
return user.getId();
}
Model类片断:
public User{
@JsonProperty("user_id")
private id;
@JsonProperty("user_name")
private name;
//getters and setters
}
当我传递一个一个JSON {"user_id":1, "user_name":"foo" }
与POST
请求User
字段是null
。在使用ModelAttribute注解时,JsonProperty注释是否可以工作?
答
它将与@RequestBody
一起使用。使用@RequestBody
,您可以向Spring MVC指定注释的对象位于HTTP请求的内部。然后,Spring MVC将尝试使用适当的HTTPMessageConverter对对象进行解码 - 您希望它将消息转换器用于json,因此您的POST请求应包含正确的Content-Type标头(例如Content-Type: application/json
)。
如果您未指定@RequestBody
Spring MVC将尝试使用请求参数填充对象(例如,如果您提交了常规HTTP POST表单)。
因此:
public String doControl(@RequestBody User user, HttpServletRequest request){...}