0

I have a json object and when it is passing through a request parameter on client side,and server side the json string is breaking from space character.

ex:

{"id":100,"age":15,"name":"sample string"}

when its come to the request.getParameter() showing like this

{"id":100,"age":15,"name":"sample

JAVASCRIPT

var location='MyAction.do?method=myMethod';
var form = '<input type="hidden" name="transactionId" value="'+getSession()+'" /><input type="hidden" name="myInfo" value='+JSON.stringify(myInfo)+' />';
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();

JAVA

String myInfo = request.getParameter("myInfo");

This is only happening when info string having space characters.how can I get the full string?

thanks.

4
  • 1
    You should share some other details with us, such as server side framework and client side code as well Commented Jun 30, 2015 at 3:55
  • I've never faced like that. Commented Jun 30, 2015 at 3:58
  • Are you sure it's a space and not a new line? Can you control how the JSON string is being passed? If you're using the querystring parameters, you should URLencode your JSON string before adding to the URL Commented Jun 30, 2015 at 4:09
  • @jasonscript yes I'm passing it as querystring.what do you mean by encoding.doing spaces to '%20'? Commented Jun 30, 2015 at 5:36

1 Answer 1

1

You can encode your values

value='+JSON.stringify(myInfo)+'

This will give the raw string with spaces etc. You can use the in-built encodeURIComponent(string) method to encode your string

var myInfo = {"id":100,"age":15,"name":"sample string"};
encodeURIComponent(JSON.stringify(myInfo));

this returns the encoded string. This doesn't contain any symbols that might confuse the browser ({}[space]&? etc)

%7B%22id%22%3A100%2C%22age%22%3A15%2C%22name%22%3A%22sample%20string%22%7D

You can then decode it using decodeURIComponent(string)

var request_value = decodeURIComponent('%7B%22id%22%3A100%2C%22age%22%3A15%2C%22name%22%3A%22sample%20string%22%7D');
JSON.parse(request_value);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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