1

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

2
  • Can you use jQuery? Its .ajax and related methods handle all the encoding for you. Commented Oct 19, 2012 at 17:07
  • I can use jquery, so I'll check those out. I'll probably just do server side parsing though. Thanks. Commented Oct 19, 2012 at 18:04

2 Answers 2

1

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&param2=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>&...
Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.