2017-04-14 3 views
0

Jquery ajaxの投稿データを@RequestBodyとしてSpringコントローラに苦労しています。Spring ControllerとJquery AjaxはJson文字列をObjectに変換できません

私はJSON文字列を送信し、コントローラでJSON文字列を取得できました。しかし、JSON Stringをjquery ajaxからコントローラー[オブジェクトとして変換できません]に送信できません。それはいつも言っている

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

::私はポンポンで同様ジャクソン依存性を持っている

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

**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が初期化:以下

は、コードスニペットです

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 Bad Request リモートアドレス:[: :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); 
    } 
関連する問題