Alex Rivera | Logout

Parsing json into java objects in spring-mvc

Asked 2010-10-13T07:59:19.587
30

I'm familiar with how to return json from my @Controller methods using the @ResponseBody annotation.

Now I'm trying to read some json arguments into my controller, but haven't had luck so far. Here's my controller's signature:

@RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(@RequestParam("json") @RequestBody SearchRequest json) {

But when I try to invoke this method, spring complains that: Failed to convert value of type 'java.lang.String' to required type 'com.foo.SearchRequest'

Removing the @RequestBody annotation doesn't seem to make a difference.

Manually parsing the json works, so Jackson must be in the classpath:

// This works
@RequestMapping(value = "/ajax/search/sync")
public ModelAndView sync(@RequestParam("json") String json) {
    SearchRequest request;
    try {
        request = objectMapper.readValue(json, SearchRequest.class);
    } catch (IOException e) {
        throw new IllegalArgumentException("Couldn't parse json into a search request", e);
    }

Any ideas? Am I trying to do something that's not supported?

Edit
Report

1 Answer

4

if you are using jquery on the client side, this worked for me:

Java:

@RequestMapping(value = "/ajax/search/sync") 
public ModelAndView sync(@RequestBody SearchRequest json) {

Jquery (you need to include Douglas Crockford's json2.js to have the JSON.stringify function):

$.ajax({
    type: "post",
    url: "sync", //your valid url
    contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
    data: JSON.stringify(jsonobject), //json object or array of json objects
    success: function(result) {
        //do nothing
    },
    error: function(){
        alert('failure');
    }
});
answered 2012-08-12T13:40:02.810

Your Answer