Spring 3 MVC @RequestBody Deserialization of custom List objects

A few things to make sure Spring and Jackson can correctly deserialize a list of custom objects:

  1. Besides having annotations turned on, you must use @RequestBody in the controller method to indicate you are reading the JSON in the POST request
  2. Make sure your AJAX request has a content-type of “application/json”.  Using Ext JS 4, this is done by sending jsonData instead of params in the Ext.Ajax.request.
  3. Jackson needs the property type to know how deserialize, but Spring doesn’t pass that along in the message converters and might not ever do that,  so you need a wrapper class
  4. If Jackson cannot deserialize your class, then Spring’s MappingJacksonHttpMessageConverter.canRead<?> fails and you get the HttpMediaTypeNotSupportedException (even if the request header has content-type of application/json).  In my case, this was two setters for one property.

I had a few of these things mixed together, so it was a little tricky to unwind, but here’s some code that will deserialize a list of “Users”.  So, that JSON looks something like (w/o the proper quotes):

[{userId: 1, name: John}, {userId: 2, name: Sally}]


// The wrapper class, so that type info (of User) is passed thru the message converters to Jackson
public class Users extends ArrayList<User> {
	private static final long serialVersionUID = 1L;

	public Users() { super(); }
}

// Example method from the controller:
	@RequestMapping(value="/status", method = RequestMethod.POST)
	public @ResponseBody Map<String, ? extends Object> status(@RequestBody Users users) {
		// handle the request here
	}

Helpful links:

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s