JSON发布到Spring Controller

2022-09-03 18:16:07

嗨,我从春季的Web服务开始,所以我正在尝试在春季+ JSON + Hibernate中开发小型应用程序。我有一些HTTP-POST问题。我创建了一个方法:

@RequestMapping(value="/workers/addNewWorker", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public String addNewWorker(@RequestBody Test test) throws Exception {
    String name = test.name;
    return name;
}

我的模型测试看起来像这样:

public class Test implements Serializable {

private static final long serialVersionUID = -1764970284520387975L;
public String name;

public Test() {
}
}

通过POSTMAN,我只是发送JSON {“name”:“testName”},我总是得到错误;

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.

我导入了杰克逊图书馆。我的 GET 方法工作正常。我不知道我做错了什么。我感谢任何建议。


答案 1

使用将 JSON 对象转换为 JSON 字符串

JSON.stringify({“name”:“testName”})

或手动。@RequestBody期望 json 字符串而不是 json 对象。

注意:字符串化函数在某些IE版本有问题,火狐它会工作

验证 Ajax 请求的语法以进行 POST 请求。进程数据:在 ajax 请求中需要 false 属性

$.ajax({ 
    url:urlName,
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser  
     processData:false, //To avoid making query String instead of JSON
     success: function(resposeJsonObject){
        // Success Action
    }
});

控制器

@RequestMapping(value = urlPattern , method = RequestMethod.POST)

public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {

    //do business logic
    return test;
}

@RequestBody-Covert Json object to java

@ResponseBody- 将 Java 对象转换为 json


答案 2

您需要为模型类中定义的所有字段包含 getter 和 setter -Test

public class Test implements Serializable {

    private static final long serialVersionUID = -1764970284520387975L;

    public String name;

    public Test() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}