The whole point of the Json()
helper method is to serialize as JSON.
If you want to return raw content, do that directly:
return Content(jsonString, "application/json");
If you have a JObject
, or a JArray
containing JObjects
, you can simply call ToString()
on the JObject
(or JArray
) to get the JSON string. For example:
JObject jo = new JObject();
jo.Add("foo", "bar");
jo.Add("fizz", "buzz");
JObject jo2 = new JObject();
jo2.Add("foo", "baz");
jo2.Add("fizz", "bang");
JArray ja = new JArray();
ja.Add(jo);
ja.Add(jo2);
string json = ja.ToString();
Console.WriteLine(json);
Resulting JSON output:
[
{
"foo": "bar",
"fizz": "buzz"
},
{
"foo": "baz",
"fizz": "bang"
}
]
If you have a regular array of JObjects, you can pass it to JsonConvert.SerializeObject()
:
JObject[] arrayOfJObjects = new JObject[] { jo, jo2 };
json = JsonConvert.SerializeObject(arrayOfJObjects, Formatting.Indented);
Console.WriteLine(json);
This gives exactly the same JSON output as shown above.
JsonConvert.SerializeObject()
also works fine on a single JObject
:
json = JsonConvert.SerializeObject(jo, Formatting.Indented);
Console.WriteLine(json);
Output:
{
"foo": "bar",
"fizz": "buzz"
}
EDIT
I just noticed the ASP.NET MVC tag on your question.
If you're inside an MVC controller method then presumably you are doing something like this:
return Json(arrayOfJObjects);
which will not work. This is because MVC uses the JavaScriptSerializer
, which does not know about Json.Net JObjects
. What you need to do in this case is create your JSON using one of the methods I listed above, then return it from your controller method using the Content
method like this:
string json = JsonConvert.SerializeObject(arrayOfJObjects);
return Content(json, "application/json");
Best Answer
Check the source to see how JsonResult is implemented. Derive from ActionResult with your DataContractJsonSerializer implementation. Right now it won't be easy to use the Json() helper method, but you could create your own helper method in a layer supertype controller. Your new helper method would return your new ActionResult derivation.