2017-04-14 120 views
0

我一直在为jQuery的ajax后数据挣扎到Spring控制器作为@RequestBody。Spring控制器和JQuery的Ajax无法将Json字符串转换为对象

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

下面的代码片段:

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

//初始化responseObject:

  <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转换的可能性仍然没有运气。

任何帮助表示赞赏。

谢谢。

+0

您在ajax请求中提到dataType为html。我认为它应该是'application/json'或者只是删除它。 –

+0

@VijendraKulhade dataType意味着预期的正确的返回类型。即使我试了一下,但仍收到的响应是相同的/*RequestURL:http://localhost:8080/testSpringmvc-1.0/ajaxhai.do 请求方法:POST 状态代码:400错误的请求 远程地址:[: :1]:8080 */ – venkatVJ

+0

你说得对我感到困惑dataType和contentType。 –

回答

0

请检查您正在尝试发送的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); 
    }