2017-02-10 24 views
0

我是新来的弹簧和ajax 我有一个json对象在我的java脚本是动态创建的 我需要发送这个json对象从java脚本使用ajax或正常提交( )从Java脚本传递Json对象到java

如果它是一个字符串,我们有隐藏的输入。

就我所知,如果我没看错的 我们不能将它存储在隐藏

我必须接受使用Java代码JSON对象。 这是我的脚本

$(document).ready(function(){ 
    // click on button submit 
    $("#save_btn").on('click', function(){ 
     alert(); 
     // send ajax 
     $.ajax({ 
      url: 'project_reg_save', // url where to submit the request 
      type : "POST", // type of action POST || GET 
      dataType : 'json', // data type 
      data : $("#reg_form").serialize(), // post data || get data 

      success : function(result) { 
       // you can see the result from the console 
       // tab of the developer tools 
       console.log(result); 
      }, 
      error: function(xhr, resp, text) { 
       console.log(xhr, resp, text); 
      } 
     }) 
    }); 
}); 

,这是我的Java代码

@Controller 
public class Save { 
    @RequestMapping("/project_reg_save") 

    public ModelAndView mymethod(@RequestParam JSONObject obj)//which is not possible { 

     System.out.println(obj); 

     return new ModelAndView("Product_reg", "msg", "product Registration"); 
    } 
} 
+0

也许尝试把它当作一个字符串,然后使用Java序列化呢? –

+0

它不是请求参数,它是请求主体。尝试将标注更改为'@ RequestBody',并在'@ RequestMapping'中添加'consumes = {MediaType.APPLICATION_JSON_VALUE}' –

回答

0

一种解决方案是

  1. 改变你的数据类型: 'JSON' 以数据类型: '文本'
  2. @RequestParam JSONObject obj to @RequestParam String obj
  3. JsonObject JsonObj = new JsonParser()。parse(obj).getAsJsonObject();

因此你得到JSON对象