如何在servlet中读取ajax发送的json

时间:2013-10-24 14:00:15

标签: java jquery ajax json servlets

我是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');
    }
});

的Servlet

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

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

3 个答案:

答案 0 :(得分:27)

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

$.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)。

答案 1 :(得分:5)

您必须使用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

答案 2 :(得分:0)

使用import org.json.JSONObject而不是import org.json.simple.JSONObject为我做了诀窍。

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