How to add a URL String in a JSON object

49.5k Views Asked by At

I need to add a URL typically in the format http:\somewebsite.com\somepage.asp. When I create a string with the above URL and add it to JSON object json

using

json.put("url",urlstring);

it's appending an extra "\" and when I check the output it's like http:\\\\somewebsite.com\\somepage.asp

When I give the URL as http://somewebsite.com/somepage.asp the json output is http:\/\/somewebsite.com\/somepage.asp

Can you help me to retrieve the URL as it is, please?

Thanks

2

There are 2 best solutions below

0
Simon Germain On BEST ANSWER

Your JSON library automatically escapes characters like slashes. On the receiving end, you'll have to remove those backslashes by using a function like replace().

Here's an example:

string receivedUrlString = "http:\/\/somewebsite.com\/somepage.asp";<br />
string cleanedUrlString  = receivedUrlString.replace('\', '');

cleanedUrlString should be "http://somewebsite.com/somepage.asp".

Hope this helps.

Reference: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(char,%20char)

0
Stephen C On

Tichodroma's answer has nailed it. You can solve the "problem" by storing valid URLs.


In addition, the JSON format requires that backslashes in strings are escaped with a second backslash. If the 2nd backslash is left out, the result is invalid JSON. Refer to the JSON syntax diagrams at http://www.json.org

The fact that the double backslashes are giving you problems actually means that the software that is reading the files is broken. A properly written JSON parser will automatically de-escape the strings. The site I linked to above lists many JSON parser libraries written in many languages. You should use one of these rather than trying to write the JSON parsing code yourself.