25

Im building a JObject myself and want to return it as ActionResult. I dont want to create and then serialize a data object

For example

public ActionResult Test(string id)
{
      var res = new JObject();
      JArray array = new JArray();
      array.Add("Manual text");
      array.Add(new DateTime(2000, 5, 23));
      res["id"] = 1;
      res["result"] = array;
      return Json(res); //???????
}
Liam
  • 27,717
  • 28
  • 128
  • 190
NeatNerd
  • 2,305
  • 3
  • 26
  • 49

2 Answers2

48

You should just be able to do this in your action method:

return Content( res.ToString(), "application/json" );
Craig W.
  • 17,838
  • 6
  • 49
  • 82
  • 1
    I was trying to use Newtonsoft Json Serializer to resolve datetime issue and did not know how to return the string I have. Thanks a lot – Faisal Jun 06 '18 at 16:21
  • [This](https://stackoverflow.com/a/23349116/712526) looks like a more robust way of handling it. Plus, you don't have to change your types from `JsonResult` to `ActionResult`. – jpaugh Oct 25 '18 at 19:33
  • @jpaugh, this post is over four years old at this point. The better way to handle this today is to use Web API rather than bending the MVC framework to build what is essentially a REST API. Also, I don't understand the second part of your statement. JsonResult is a subclass of ActionResult. Finally, writing more code to do what the framework will do for you automatically is never a good solution IMO. – Craig W. Oct 25 '18 at 21:09
  • There are a number of limitations in the built-in JSON serializer that Newtonsoft's JSON.NET overcomes, so this topic is still relevant. (And, while I can't change the version of the tech stack I'm on, I'm sure I'm not the only one 4 (or more) years behind the curve.) – jpaugh Oct 25 '18 at 21:53
  • My second statement was referring to the result type of the expression, which is `ContentResult` for the above; whereas I was already using `JsonResult`. – jpaugh Oct 25 '18 at 21:56
6

In case, if you take care of JSON Formatting , just return JSON Formatted string

public string Test(string id)
{
      var res = new JObject();
      JArray array = new JArray();
      array.Add("Manual text");
      array.Add(new DateTime(2000, 5, 23));
      res["id"] = 1;
      res["result"] = array;
      return YourJSONSerializedString;
}

else Use built in JsonResult(ActionResult)

    public JsonResult Test(string id)
    {

          return Json(objectToConvert);
    }
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120