2013-11-20 46 views
0

我试图将一个对象发布到使用Spring MVC实现的我的RESTful服务,但它不起作用。将json参数发布到REST服务时出错

在我的测试页,我有:

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); 
    } 
}); 

我使用json2.js到字符串化我的对象。

在我的控制,我有:

@RequestMapping(value="/canvass/test", method = RequestMethod.POST) 
public void createTest(@RequestParam TestObj tobj) 
     throws ServiceOperationException { 
    // test method 
    int i = 0; 
    System.out.println(i); 
} 

我的实体类是:

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; 
    } 

} 

当我发布对象到控制器我得到一个HTTP 400错误:

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

我做错了什么?这似乎是我发送的参数/对象的格式不正确,但我不明白为什么...

回答

1

您正在使用JSON数据进行POST,而在您的控制器中,您试图将其解释为参数(即?tobj=someValue)。

尝试玩弄,而不是执行以下操作:

@RequestMapping(value="/canvass/test", method = RequestMethod.POST) 
public void createTest(@RequestBody TestObj tobj) 
     throws ServiceOperationException { 
    // test method 
    int i = 0; 
    System.out.println(i); 
} 

此外,你不必巢您的JSON数据:

的那么{id: 1, desc: 'yesh'}代替{ tobj: {id: 1, desc: 'yesh'}}

随着Jackons使用在水下,这应该起作用。

+0

是的,你是对的!谢谢! – davioooh