Reputation: 270
I'm sending a json object through ajax to a java servlet. The json object is key-value type with three keys that point to arrays and a key that points to a single string. I build it in javascript like this:
var jsonObject = {"arrayOne": arrayOne, "arrayTwo": arrayTwo, "arrayThree": arrThree, "string": stringVar};
I then send it to a java servlet using ajax as follows:
httpRequest.open('POST', url, true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.setRequestHeader("Connection", "close");
var jsonString = jsonObject.toJSONString();
httpRequest.send(jsonString);
This will send the string to my servlet, but It isn't showing as I expect it to. The whole json string gets set to the name of one of my request's parameters. So in my servlet if I do request.getParameterNames(); It will return an enumeration with one of the table entries' key's to be the entire object contents. I may be mistaken, but my thought was that it should set each key to a different parameter name. So I should have 4 parameters, arrayOne, arrayTwo, arrayThree, and string. Am I doing something wrong or is my thinking off here? Any help is appreciated.
Thanks
Upvotes: 1
Views: 2272
Reputation: 1201
It is the expected behavior, you're converting your object to string (using toJSONString) and its is being send as a request parameter. You may want to parse the JSON value on the serverside using libraries such as Jackson, Jettison or XStream see http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Upvotes: 1
Reputation: 13941
When you set the content-type to application/x-www-form-urlencoded
, you're telling the server that the request content is going to be a string of the form "param1=value1¶m2=value2..."
. But your actual content is just a single value; the x-www-form-urlencoded
content type has nothing to do with JSON. If you want to pass the request as JSON, you'll need to set the content-type to application/json
and then have a JSON parser on the server side to parse it and extract the key/value pairs.
Alternatively, you could keep the x-www-form-urlencoded type
, loop through your JSON object and, for every key/value pair, serialize the value as a JSON string and URL-encode, and use that to build up a request string that looks like:
arrayOne=<arrayOne JSON string>&arrayTwo=<arrayTwo JSON String>&...
Upvotes: 1