有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将json参数发布到REST服务时发生java错误

我试图将一个对象发布到使用Spring MVC实现的RESTful服务中,但它不起作用

在我的测试页面中,我有:

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) 个答案

  1. # 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'}}

    如果在水下使用千斤顶,这应该会起作用