- 10 months ago 44
ASP.NET (C#) Question

Can't get < to show up in JSON string

Ok, first hear me out by looking at this url:

Notice how the Description string has non-encoded html in it such as <, >, etc.

Here is how I returned my JSON using ASP.NET 3.5 and C#:

context.Response.ContentType = "text/plain";
context.Response.Charset = Encoding.UTF8.ToString();

int i = 1;

List<Product> products = GetTestProducts();
List<CrImageList> imageList = new List<CrImageList>();

foreach(Product p in products)
string imageTag = HttpUtility.HtmlEncode(string.Format(@"<img src=""{0}"" alt="""">", ImageUrl(p.Image, false)));

imageList.Add(new CrImageList{ImageTag = imageTag});

string jsonString = imageList.ToJSON();

And here is the JSON returned by this code that is called when I hit my .ashx and it calls this code in the method that contains it:

[{"ImageTag":"&lt;img src=&quot;; alt=&quot;&quot;&gt;"},{"ImageTag":"&lt;img src=&quot;; alt=&quot;&quot;&gt;"}]

Now how can I get the encoded characters to actually show up as html chars in the text string returned by my JSON?

I want < to show < and so on just like Flickr was able to do in their JSON.

If I take out the HtmlEncode:

string.Format(@"", ImageUrl(p.Image, false));

Then I start to get the /u00 in my string:

[{"ImageTag":"\u003cimg src=\"\" alt=\"\"\u003e"},

So why doesn't Flickr's JSON return anything but clean html in their description?


Are you using the string elsewhere? If you're using it in Javascript, it shouldn't matter that the <> characters are being escaped.

<script type="text/javascript" defer="defer">
document.body.innerHTML = "\u003cimg src=\"\" alt=\"\"\u003e";

Is the same as:

<script type="text/javascript" defer="defer">
document.body.innerHTML = "<img src=\"\" alt=\"\">";

In Javascript, those strings are pretty much the same when it comes to doing something with them.