Samo Samo - 5 months ago 22
JSON Question

Returning a JObject as Json from an endpoint

I'd like to do something like this:

var taxonomyJson = JObject.FromObject(taxonomy);
return Json(taxonomyJson, JsonRequestBehavior.AllowGet);


I've tried converting
taxonomyJson
to a
JToken
and various other properties. I've tried wrapping, etc. But it always throws errors.

Of course, I can return
taxonomyJson.ToString()
, but I don't like that very much because then it wraps an extra double quota around my string which my JavaScript will have to strip off before calling
JSON.parse()
on it.

If
Json()
can handle serializable objects, why can't it handle a
JObject
or a
JToken
that has the JSON already prepared?

Answer

How about:

return Content(taxonomyJson.ToString(), "application/json");

And this for an array:

var jObject = JObject.FromObject(new { Payload = arrayOfJObjects });
return Content(jObject.ToString(), "application/json");
Comments