views:

82

answers:

2

Are the any functions in C# that handle escape/unescape like JavaScript?

I have a JSON string like this:

{"Feeds":[{"Url":"www.test.com","FeedType":"Twitter"},{"Url":"www.test2.com","FeedType":"Youtube"}]}

Which looks like this after escape()

%7B%22Feeds%22%3A%5B%7B%22Url%22%3A%22www.test.com%22%2C%22FeedType%22%3A%22Twitter%22%7D%2C%7B%22Url%22%3A%22www.test2.com%22%2C%22FeedType%22%3A%22Youtube%22%7D%5D%7D

In my C# code I would like to unescape this string so that it looks exactly the same as it did before the escape()

Is this possible?

+6  A: 

HttpUtility.UrlDecode should do the trick.

Justin Niessner
@Timwi - You are correct. I mis-read. Updated. Just out of curiosity, why did you roll your own code (now deleted) to do the same thing instead of re-using what .NET provides?
Justin Niessner
Thx, I tried `HttpUtility.HtmlDecode` but it did not work, but when I see your answer I see that `UrlDecode` does something that `HtmlDecode` did not do.
Martin
@Martin - Yeah. `HtmlDecode` is for decoding escaped HTML characters. URL Encoding involves more rules.
Justin Niessner
@Justin: Well firstly because I didn’t know about it at the time. Secondly because `HttpUtility` requires a reference to `System.Web.dll`, which is filled to the rim with stuff I have no use for. But thirdly because I enjoy rolling my own... I rolled my own webserver too... :-p
Timwi
+2  A: 

escape() is equivalent to

HttpUtility.UrlDecode(str, System.Text.Encoding.Default);

By default the UrlDecode uses UTF8 while escape() don't.

BrunoLM
UTF8 is backward compatible with ASCII so, unless I'm mis-understanding something, you shouldn't have to pass in the encoding.
Justin Niessner
This is wrong... escape() is actually equivalent to `HttpUtility.UrlDecode(str, Encoding.Default)`, which means two things: ① it depends on your system locale settings; and ② it is obsolete 1990s 8-bit technology and incompatible with UTF-8. (The second paragraph is correct though.)
Timwi
@Justin Niessner: As you said, it is backward `compatible`. Not equivalent. And I want to give emphasis on `backward`, don't even think it's compatible the other way.
BrunoLM