2013-11-20 49 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