Java JSON 发布到 Spring Controller

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18550418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:58:47  来源:igfitidea点击:

JSON post to Spring Controller

javajsonspringspring-mvc

提问by user2239655

Hi I am starting with Web Services in Spring, so I am trying to develop small application in Spring + JSON + Hibernate. I have some problem with HTTP-POST. I created a method:

嗨,我从 Spring 中的 Web 服务开始,所以我正在尝试在 Spring + 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;
}

And my model Test looks like:

我的模型 Test 看起来像:

public class Test implements Serializable {

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

public Test() {
}
}

By POSTMAN I am sending simply JSON {"name":"testName"} and I always get error;

通过邮递员,我只发送 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.

I imported Hymanson library. My GET methods works fine. I don't know what I'm doing wrong. I am grateful for any suggestions.

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

采纳答案by Vineeth Bhaskaran

Convert your JSON object to JSON String using

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

JSON.stringify({"name":"testName"})

JSON.stringify({"name":"testName"})

or manually. @RequestBody expecting json stringinstead of json object.

或手动。@RequestBody 需要 json 字符串而不是 json 对象。

Note:stringify function having issue with some IE version, firefox it will work

注意:stringify 函数在某些 IE 版本中存在问题,firefox 可以使用

verify the syntax of your ajax request for POST request. processData:falseproperty is required in ajax request

验证 POST 请求的 ajax 请求的语法。processData:false属性在 ajax 请求中是必需的

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

Controller

控制器

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

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

    //do business logic
    return test;
}

@RequestBody-Covert Json object to java

@RequestBody- 将 Json 对象转换为 Java

@ResponseBody- convert Java object to json

@ResponseBody- 将 Java 对象转换为 json

回答by Vin Tsie

Try to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.

尝试使用 application/* 代替。并使用 JSON.maybeJson() 检查控制器中的数据结构。

回答by Aman Goel

Do the following thing if you want to use json as a http request and response. So we need to make changes in [context].xml

如果您想使用 json 作为 http 请求和响应,请执行以下操作。所以我们需要在 [context].xml 中进行更改

<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonMessageConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingHymanson2HttpMessageConverter">
</beans:bean>   

MappingHymanson2HttpMessageConverter to the RequestMappingHandlerAdapter messageConverters so that Hymanson API kicks in and converts JSON to Java Beans and vice versa. By having this configuration, we will be using JSON in request body and we will receive JSON data in the response.

MappingHymanson2HttpMessageConverter 到 RequestMappingHandlerAdapter messageConverters 以便 Hymanson API 启动并将 JSON 转换为 Java Beans,反之亦然。通过此配置,我们将在请求正文中使用 JSON,我们将在响应中接收 JSON 数据。

I am also providing small code snippet for controller part:

我还为控制器部分提供了小代码片段:

    @RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)

    public @ResponseBody Employee getDummyEmployee() {
    logger.info("Start getDummyEmployee");
    Employee emp = new Employee();
    emp.setId(9999);
    emp.setName("Dummy");
    emp.setCreatedDate(new Date());
    empData.put(9999, emp);
    return emp;
}

So in above code emp object will directly convert into json as a response. same will happen for post also.

所以在上面的代码中,emp 对象将直接转换为 json 作为响应。帖子也会发生同样的情况。

回答by Ameya Pandilwar

You need to include the getters and setters for all the fields that have been defined in the model Testclass --

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

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

}

回答by Yu Chai

see here

这里

The consumable media types of the mapped request, narrowing the primary mapping.

映射请求的可消费媒体类型,缩小了主映射的范围。

the producer is used to narrow the primary mapping, you send request should specify the exact header to match it.

生产者用于缩小主映射的范围,您发送的请求应指定准确的标头以匹配它。