I am configuring a RESTful web service via Spring, with various representations, including JSON. I want the interface to be symmetrical, meaning the format of an object serialized to JSON via a GET is also the format that a POST/PUT would accept. Unfortunately I can only get GETs to work.
Here's my configuration for sending and receiving JSON, which consists of a JSON message converter and view:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</util:list>
</property>
</bean>
<bean id="contentNegotiatingViewResolver" class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<util:map>
<entry key="json" value="application/json"/>
</util:map>
</property>
<property name="defaultViews">
<util:list>
<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
</util:list>
</property>
</bean>
When I hit a controller with a GET to return an object, for example, a Book, it outputs something like this.
{"book":{"isbn":"1234","author":"Leo Tolstoy","title":"War and Peace"}}
If I turn around and re-submit some similar JSON via a POST or PUT, Spring cannot consume it, complaining about Unrecognized field "book" (Class com.mycompany.Book), not marked as ignorable
. Additionally, if I strip off the "book" wrapper element (I'd rather not, but just to see what happens), I get a 400 BAD REQUEST. In either case, my controller code is never hit.
Here's my controller - I'd rather not have any JSON-specific code here (or annotations on my classes being marshalled/unmarshalled) as they will have multiple representations - I want to use Spring's decoupled MVC infrastructure that pushes that kind of thing (marshalling/view resolving/etc.) into configuration files:
@RequestMapping(method=PUT, value="/books/{isbn}")
@ResponseStatus(NO_CONTENT)
public void saveBook(@RequestBody Book book, @PathVariable String isbn) {
book.setIsbn(isbn);
bookService.saveBook(book)
}
@RequestMapping(method=GET, value="/books/{isbn}")
public ModelAndView getBook(@PathVariable String isbn) {
return new ModelAndView("books/show", "book", bookService.getBook(isbn));
}