【问题标题】:How to read json sent by ajax in servlet如何在servlet中读取ajax发送的json
【发布时间】:2013-11-03 06:58:52
【问题描述】:

我是java新手,在这个问题上苦苦挣扎了2天,终于决定在这里问。

我正在尝试读取 jQuery 发送的数据,以便在我的 servlet 中使用它

jQuery

var test = [
    {pv: 1000, bv: 2000, mp: 3000, cp: 5000},
    {pv: 2500, bv: 3500, mp: 2000, cp: 4444}
];

$.ajax({
    type: 'post',
    url: 'masterpaket',
    dataType: 'JSON',
    data: 'loadProds=1&'+test, //NB: request.getParameter("loadProds") only return 1, i need to read value of var test
    success: function(data) {

    },
    error: function(data) {
        alert('fail');
    }
});

小服务程序

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
   if (request.getParameter("loadProds") != null) {
      //how do i can get the value of pv, bv, mp ,cp
   }
}

非常感谢您提供的任何帮助。

【问题讨论】:

  • 我不太了解javascript。它如何序列化vartest

标签: java jquery ajax json servlets


【解决方案1】:

使用 import org.json.JSONObject 而不是 import org.json.simple.JSONObject 对我有用。

How to create Json object from String containing characters like ':' ,'[' and ']' in Java

【讨论】:

    【解决方案2】:

    您必须使用 JSON 解析器将数据解析到 Servlet 中

    import org.json.simple.JSONObject;
    
    
    // this parses the json
    JSONObject jObj = new JSONObject(request.getParameter("loadProds")); 
    Iterator it = jObj.keys(); //gets all the keys
    
    while(it.hasNext())
    {
        String key = it.next(); // get key
        Object o = jObj.get(key); // get value
        System.out.println(key + " : " +  o); // print the key and value
    }
    

    您将需要一个 json 库(例如 Jackson)来解析 json

    【讨论】:

      【解决方案3】:

      除非您正确发送,否则您将无法在服务器上解析它:

      $.ajax({
          type: 'get', // it's easier to read GET request parameters
          url: 'masterpaket',
          dataType: 'JSON',
          data: { 
            loadProds: 1,
            test: JSON.stringify(test) // look here!
          },
          success: function(data) {
      
          },
          error: function(data) {
              alert('fail');
          }
      });
      

      您必须使用JSON.stringify 将您的 JavaScript 对象作为 JSON 字符串发送。

      然后在服务器上:

      String json = request.getParameter("test");
      

      您可以手动解析json 字符串,或使用任何库(我推荐gson)。

      【讨论】:

        猜你喜欢
        • 2016-12-10
        • 1970-01-01
        • 2012-04-07
        • 1970-01-01
        • 2020-01-27
        • 1970-01-01
        • 2017-05-28
        • 1970-01-01
        • 2012-01-27
        相关资源
        最近更新 更多