【问题标题】:Spring Controller and Jquery Ajax are unable to convert Json string to ObjectSpring Controller 和 Jquery Ajax 无法将 Json 字符串转换为 Object
【发布时间】:2017-04-14 14:50:01
【问题描述】:

我一直在努力将 Jquery ajax 以 @RequestBody 的形式发布到 Spring 控制器中。

我能够发送 JSON 字符串并在控制器中捕获 JSON 字符串。但是,无法将 JSON 字符串从 jquery ajax 发送到控制器 [无法转换为对象]。

下面是代码sn-p:

 **Ajax Call:**   


          function postLoad(){
                $.ajax({
                    type : 'POST',
                    url : "ajaxhai.do",
                    contentType : "application/json",
                    cache : false,
                    data : responseObject, **//json-String**
                    dataType :"html",
                    success : function(data, textStatus) {
                        console.log("POST success");
                        $("#ajaxContent").html(data);
                    },
                    error : function(request, status, error) {
                        console.log("failed" + error);
                    }
                });
            }

// 响应对象初始化:

            <c:if test='${not empty ajitems}'>
                var responseObject = JSON.stringify('${ajitems}');
            </c:if>  
   // ${ajitems}--> is the model attribute and setting it in javascript to //send it back to controller through ajax call

    //Controller:
    @RequestMapping(value = "ajaxhai.do", method = RequestMethod.POST,consumes="application/json") **//unable to convert to requestBody**
        public  String testAjaxPost(@RequestBody AjaxDto[] ajaxRes, Model model,
                HttpServletRequest request, HttpServletResponse response) {

            System.out.println(ajaxRes);

            return "ajaxform";
        }

我在 pom 中也有杰克逊依赖:

<dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.7.3</version>
        </dependency>

它总是在说:

jquery-3.2.1.min.js:4 POST http://localhost:8080/testSpringmvc-1.0/ajaxhai.do 400 (Bad Request)

但是当我以以下方式更改控制器时,它就像魅力一样工作:

@RequestMapping(value = "ajaxhai.do", method = RequestMethod.POST,consumes="application/json")**//Please note : here it is String and not Object[]**
    public  String testAjaxPost(@RequestBody String ajaxRes, Model model,
            HttpServletRequest request, HttpServletResponse response) {

        System.out.println(ajaxRes);
        Gson gson = new Gson();
        TestAjaxDto[] mcArray = gson.fromJson(ajaxRes, TestAjaxDto[].class);
        List<TestAjaxDto> mcList = new ArrayList<TestAjaxDto>(Arrays.asList(mcArray));
        System.out.println(mcList);
        return "ajaxform";
    }

我在这里缺少什么?我已经尝试了自动 json 转换的所有可能性,但仍然没有运气。

感谢任何帮助。

谢谢。

【问题讨论】:

  • 您在 ajax 请求中提到 dataType 为 html。我认为应该是application/json 或者直接删除它。
  • @VijendraKulhade dataType 是预期的返回类型。即使我试了一下,但收到的响应仍然相同 /*RequestURL:localhost:8080/testSpringmvc-1.0/ajaxhai.do Request Method:POST Status Code:400 Bad Request Remote Address:[::1]:8080*/
  • 你说得对,我对 dataType 和 contentType 感到困惑。

标签: jquery ajax spring-mvc


【解决方案1】:

当您期望控制器中的数组时,请检查您尝试发送的 json。 json有问题。 还要检查您是否注册了MappingJackson2HttpMessageConverter 我认为您应该这样做。

<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="objectMapper">
            <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
                  p:autoDetectFields="false"
                  p:autoDetectGettersSetters="false"
                  p:failOnEmptyBeans="false"
                  p:indentOutput="true">
            </bean>
        </property>
    </bean>

这是一个很好的例子。 Ajax 请求

var requestObject = [{"product_Name":"One Product","descripction":"Essentials","category":null,"price":"100.00","mfg_Date":null,"image":null},
    {"product_Name":"two Product","descripction":"Essentials 2","category":null,"price":"120.00","mfg_Date":null,"image":null}];
    $.ajax({
            type : 'POST',
            url : "services/product",
            cache : false,
            contentType:"application/json;charset=utf-8",
            data : JSON.stringify(requestObject),//json-String**
            dataType :"application/json;charset=utf-8",
            success : function(data, textStatus) {
                console.log("POST success"+data);
               /* $("#ajaxContent").html(data);*/
            },
            error : function(request, status, error) {
                console.log("failed" + error);
            }
        });

这是接受此请求的控制器。

@RequestMapping(value = "/product",produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
            method = RequestMethod.POST,
            consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public @ResponseBody
    ResponseEntity<List<Product>> createProduct(@RequestBody  Product[] products) {
        return new ResponseEntity<List<Product>>(Arrays.asList(products), HttpStatus.OK);
    }

【讨论】:

    猜你喜欢
    • 2020-12-26
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多