views:

744

answers:

2

Hi folks,

i have the following data as a string in my Action method:

string json = "[[1,2],[3,4],[5,6]]";

Simple.

When I call the Json view, it encapsulates the result in two double quotes. This stops the client side javascript from loading this result into a javascript object.

eg. 
return Json(json);

result => "[[1,2],[3,4],[5,6]]"

but, if i return the result as a ContentResult, then the result gets loaded into a javascript object and I can do whatever I need to do, with it.

eg.
return new ContentResult
{
    Content = json,
    ContentType = "application/json",
    ContentEncoding =System.Text.Encoding.UTF8
};

result => [[1,2],[3,4],[5,6]]      
          (notice how the double quotes are missing?).

So, can someone explain what i should be doing right, please? I feel like the ContentResult is not the right way to do it.

+2  A: 

I would guess that the JsonResult wants to serialize the object you pass in. And because your string is more-or-less 'serialized' (in Json terms) all it can do is see that the object is a string, and in 'Json land', string literals get quotes around them.

Maybe if you change your string into a strongly typed List/Collection/Array of some sort (that represents the data like you have there in the string) it will serialize correctly.

cottsak
+1  A: 

I realise that you probably want a server side solution - but just in case you can't find one then you can evaluate the returned string in Javascript client side:

var jsonResult = eval(resultWithQuotes);

Please note that you should only do this if you are getting your result from a safe source as this could cause malicious script to be loaded.

Darko Z