Q:

Error posting json parameter to REST service

I'm trying to POST an object to my RESTful service implemented using Spring MVC, but it doesn't work.
In my test page I have:
var obj = { tobj: {id: 1, desc: 'yesh'}};
$.ajax({
    url : 'http://localhost:8180/CanvassService/canvass/test',
    type : 'POST',
    data : JSON.stringify(obj),
    contentType : 'application/json; charset=utf-8',
    dataType : 'json',
    async : false,
    success : function(msg) {
        alert(msg);
    }
});

I'm using json2.js to stringify my object.
In my controller I have:
@RequestMapping(value="/canvass/test", method = RequestMethod.POST)
public void createTest(@RequestParam TestObj tobj)
        throws ServiceOperationException {
    // test method
    int i = 0;
    System.out.println(i);
}

My entity class is:
public class TestObj {

    private int id;
    private String desc;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

}

when I post the object to the controller I get an HTTP 400 error: 

HTTP Status 400 - Required TestObj parameter 'tobj' is not present

What I'm doing wrong? It seems the format of the parameter/object I'm sending is not correct, but I cannot understand why...

A:

You are doing a POST with JSON data, while in your controller you are trying to interpret it as a parameter (ie. ?tobj=someValue).
Try to play around with the following instead:
@RequestMapping(value="/canvass/test", method = RequestMethod.POST)
public void createTest(@RequestBody TestObj tobj) 
        throws ServiceOperationException {
    // test method
    int i = 0;
    System.out.println(i);
}

In addition, you don't have to nest your JSON data:
So {id: 1, desc: 'yesh'} instead of { tobj: {id: 1, desc: 'yesh'}}
With Jackons used under water, this should work.

