如何根据Jackson注释配置spring mvc来填充@RequestMapping的参数?

时间:2017-07-01 13:50:02

标签: java spring forms spring-mvc

Jackson注释可用于序列化对象,但解决请求参数无效。

有一个杰克逊注释的课程如下:

public class Role{
    @JsonProperty(
        value = "description", 
        defaultValue = "description", 
        required = false, 
        access = Access.READ_WRITE)
    private String description;

    @JsonProperty(
        value = "code_name", 
        defaultValue = "permission", 
        required = true, 
        access = Access.READ_WRITE)
    private String codeName;

    ...
}

如您所见,属性codeName在json或xml中被序列化为code_name。例如,获得一个角色是:

@RequestMapping(value = "{id}", method = RequestMethod.GET)
public Role getRole(@PathVariable id){
    ...
}

结果是:

{
  "description": "..",
  "code_name": ".."
}

这是我的mvc config:

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
        <bean
            class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper" />
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

现在,假设有一个请求图如下:

@RequestMapping(value = "new", method = RequestMethod.POST)
public Role create(Role role) {
    ...
}

我在表单中填写名为description和code_name的字段并发送到服务器。但是,描述只是设置为输入角色,而codeName为null。

顺便说一句,如果表单字段名称替换为codeName,则可以。

1 个答案:

答案 0 :(得分:0)

你需要使用

@RequestMapping(value = "new", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public Role create(@RequestBody Role role) {