1

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I passed using JSON.stringify() function, but i am getting only null value when i parse it. Then i found that the value passed from jquery arrives as parametername in jsp. But even after passing the parametername directly to getJSONObject method, only null value is returned.
@SantronManibharathi I know very little about JSP so cant help you there sorry ... have a search for other questions on here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.