【问题标题】:Error posting json parameter to REST service将 json 参数发布到 REST 服务时出错
【发布时间】:2013-11-20 10:38:57
【问题描述】:

我正在尝试将一个对象发布到我使用 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 状态 400 - 所需的 TestObj 参数“tobj”不存在

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

【问题讨论】:

    标签: java json spring rest spring-mvc


    【解决方案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 在水下使用,这应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 2016-02-17
      • 1970-01-01
      相关资源
      最近更新 更多