tags:

views:

133

answers:

2

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

http://api.flickr.com/services/feeds/photos_public.gne?format=json

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});
    i++;
}

string jsonString = imageList.ToJSON();
context.Response.Write(jsonString);

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;http://www.ourdomain.com/image/540.jpg&amp;quot; alt=&quot;&quot;&gt;"},{"ImageTag":"&lt;img src=&quot;http://www.ourdomain.com/image/642.jpg&amp;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=\"http://www.xxx.com/cat_image/540.jpg\" alt=\"\"\u003e"},
...

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

+1  A: 

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=\"http://www.xxx.com/cat_image/540.jpg\" alt=\"\"\u003e";
</script>

Is the same as:

<script type="text/javascript" defer="defer">
document.body.innerHTML = "<img src=\"http://www.xxx.com/cat_image/540.jpg\" alt=\"\">";
</script>

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

Andy E
+1  A: 

If you don't want the values encoded, then why are you running them through the HttpUtility.HtmlEncode method?

If the ToJSON is not something you can change to stop unicode encoding the character, then you'll just have to do a replace after calling it...

string jsonString = imageList.ToJSON();
jsonString = jsonString.Replace("\u003c", "<").Replace("\u003e", ">");
context.Response.Write(jsonString);
Josh Stodola
I took off the Encode and then got \u003 which I had no idea what that was...
CoffeeAddict
It is unicode. I would venture to guess your JSON encoder is defaulting to some form of unicode. Regardless, the client should be able to interpret it.
Josh Stodola