Reputation: 642
I want to create a json object in jquery and process it in jsp and return back in json format. I created a json object and posted to a jsp file:
$.post("processDropDown.jsp", $('#fields tr td input').serializeArray(),
function(data) {
alert(data);
});
In jsp file i read the parameters and put in jsonobject, but json exception-null object exception is returned.
JSONObject inp = new JSONObject();
Enumeration enumeration = request.getParameterNames();
try {
while (enumeration.hasMoreElements()) {
String parameterName = (String) enumeration.nextElement();
out.print("\nParameter = " + parameterName+"\n");
inp = inp.getJSONObject(request.getParameter(parameterName));
out.print("::" + inp.toString());
}
} catch(Exception ex) {
out.print(ex);
}
The JSON.stringify() method returns the following output in client before i pass it to the jsp.
JSON.stringify($('#fields tr td input').serializeArray());
[{"name":"valueField","value":"12"},{"name":"textField","value":"Twelve"},{"name":"valueField","value":"34"},{"name":"textField","value":"ThirtyFour"}]
Upvotes: 1
Views: 1275
Reputation: 38147
Change
$.post("processDropDown.jsp",
$('#fields tr td input').serializeArray(),
function(data) {
alert(data);
}
);
to
$.post("processDropDown.jsp",
JSON.stringify($('#fields tr td input').serializeArray()),
function(data) {
alert(data);
}
);
You were posting an Object Literal rather JSON. Good read about Object vs JSON here
Note this from the .serializeArray()
docs :
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements.
Emphasis mine ...
Upvotes: 2