How to read json sent by ajax in servlet
You won't be able to parse it on the server unless you send it properly:
$.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'); }});
You must use JSON.stringify
to send your JavaScript object as JSON string.
And then on the server:
String json = request.getParameter("test");
You can parse the json
string by hand, or using any library (I would recommend gson).
You will have to use the JSON parser to parse the data into the Servlet
import org.json.simple.JSONObject;// this parses the jsonJSONObject jObj = new JSONObject(request.getParameter("loadProds")); Iterator it = jObj.keys(); //gets all the keyswhile(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}
You will need a json library (e.g Jackson) to parse the json