user1520494
user1520494

Reputation: 1184

Encoding JSON serialized for URL

I have to create a webrequest using HTTP GET and I have to add on the url a JSON serialized and encoded with all parameters.

But I have a problem when I'm encoding the serialized object, they encode also symbols like "{" and ":"

I would like to know what I have to do in order to encode the serialized object like the followed above:

Serialized Object:

{\"Name\":\"Bob\"}

Encoded With HttpUtility.Utility, or another encoder will encode all symbols:like "{" ":"

"%7b%22Name%22%3a%22Bob%22%2

What I'm looking for:

http://tmpserviceURL.test?parameters={%20%22Name%22:%20%22Bob%22}

Upvotes: 0

Views: 5860

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129797

@Ant P is correct: you want those characters to be encoded. It is a bad idea not to encode them.

HttpUtility.UrlEncode and other similar methods encode {, } and : because they MUST do so per section 2.2 of the Uniform Resource Locators specification (RFC 1738).

From page 2:

Octets [within a URL] must be encoded if they have no corresponding graphic character within the US-ASCII coded character set, if the use of the corresponding character is unsafe, or if the corresponding character is reserved for some other interpretation within the particular URL scheme.

The spec goes on to define : as being in the set of "reserved" characters (those that have special meaning within a URL), and defines { and } as being in the set of "unsafe" characters (those that are known to be sometimes modified by gateways and other transport agents).

So, in short, if you send these characters unencoded in a URL, then you risk the URL not being interpretted correctly, or the data being corrupted by the time it reaches its destination. It may work sometimes, but you can't rely on it always working.

If you really feel you must ignore the URL spec, then you will have to roll your own URL encoder that does not encode those particular characters. I doubt you're going to find an off-the-shelf encoder that allows you to do this.

Upvotes: 2

Related Questions