Spring REST jackson not marshalling on POST request
Im using spring 4 and have added jackson-databind so I can get the request/reponse object marshalled.. It works when I return the object from a GET request, but the POST request object is not being populated.. It is NOT null so it is being instantiated
I have tried it using an HttpEntity for the method param to see if I was getting the JSON object and it was in the body of the entity. I could then manually marshal it..
I'm trying to figure out what is missing or mis-configured to have jackson
This is the method where the object is instantiated but not populated. Im using Spring 4 and the controller is annotated with @RestController
which combines @Controller
and @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);
}
Here is the JSON:
{
"id": 12,
"lastName": "Test",
"firstName": "Me"
}
This is the user object: 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;
}
}
I also have the jackson mapper defined in my context file. Although the docs stated this didn't have to be done. It did work without it
<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>
尝试在您的方法调用中使用@RequestBody
注释
@RequestMapping(value="/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity <?> getUser(@RequestBody final User user){
您在方法中缺少批注调用@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);
}
The responsed provided were correct. I did need to add the @RequestBody
to the method..I mis-read the docs.. it is only the @ResponseBody
and @Controller
that are added using @RestController
. With that I do not need to add the @ResponseBody
to the return object