首页 文章

Spring REST jackson没有在POST请求上编组

提问于
浏览
1

我使用spring 4并添加了jackson-databind,因此我可以获取请求/响应对象编组..当我从GET请求返回对象时,它工作,但POST请求对象没有被填充..它不是null所以它正在被实例化

我已经尝试使用HttpEntity作为方法参数来查看我是否获得了JSON对象并且它位于实体的主体中 . 然后我可以手动编组它..

我试图弄清楚缺少什么或错误配置 Jackson

这是实例化对象但未填充对象的方法 . 我使用Spring 4,控制器用 @RestController 注释,它结合了 @Controller@ResponseBody

@RequestMapping(value="/create", method = RequestMethod.POST, consumes =  MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> getUser(User user) {
    log.debug("got user: " + user.getId());

    return new ResponseEntity<>(HttpStatus.OK);
}

这是JSON:

{
"id": 12,
"lastName": "Test",
"firstName": "Me"
}

这是用户对象:public class User {private int id; private String lastName; private String firstName; public User(){}

public User(int id, String lname, String fname) {
    this.id = id;
    this.lastName = lname;
    this.firstName = fname;
}
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
}

我还在我的上下文文件中定义了jackson映射器 . 虽然文档说明没有必要这样做 . 没有它它确实有效

<beans:bean
 class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonMessageConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>
 <beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>

3 回答

  • 1

    尝试在方法调用中使用 @RequestBody 注释

    @RequestMapping(value="/create", method = RequestMethod.POST, consumes =  MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody ResponseEntity <?> getUser(@RequestBody final User user){
    
  • 1

    您在方法中缺少注释调用@RequestBody,如果我没有错,您还需要添加@ResponseBody .

    @RequestMapping(value="/create", method = RequestMethod.POST, consumes =  MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody ResponseEntity<?> getUser(@RequestBody User user) {
        log.debug("got user: " + user.getId());
    
        return new ResponseEntity<>(HttpStatus.OK);
    }
    
  • 0

    答复者提供的是正确的 . 我确实需要将 @RequestBody 添加到方法中 . 我误读了文档..它只是使用 @RestController 添加的 @ResponseBody@Controller . 有了它,我不需要将 @ResponseBody 添加到返回对象

相关问题