如何在servlet中读取ajax发送的json
我是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 } }
我非常感谢您提供的任何帮助。
除非您正确发送,否则您将无法在服务器上解析它:
$.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 )。
您必须使用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
使用jackson API读取和写入JSON数据,如下所示:
publicvoid doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ // This will store all received articles List articles = new LinkedList (); if (request.getParameter("loadProds") != null) { // 1. get received JSON data from request BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String json = ""; if(br != null){ json = br.readLine(); } // 2. initiate jackson mapper ObjectMapper mapper = new ObjectMapper(); // 3. Convert received JSON to Article Article article = mapper.readValue(json, Article.class); // 4. Set response type to JSON response.setContentType("application/json"); // 5. Add article to List articles.add(article); // 6. Send List as JSON to client mapper.writeValue(response.getOutputStream(), articles); } }
使用导入org.json.JSONObject而不是导入org.json.simple.JSONObject为我做了诀窍。
请参阅如何从String中创建包含’:’,'[‘和’]’等字符的Json对象 。