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); //???????
}
1
  • 2
    @Liam this question came first so how can it be a duplicate? You've flagged the wrong question.
    – user692942
    Commented Oct 26, 2017 at 12:08

2 Answers 2

48

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

return Content( res.ToString(), "application/json" );
5
  • 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
    Commented Jun 6, 2018 at 16:21
  • This looks like a more robust way of handling it. Plus, you don't have to change your types from JsonResult to ActionResult.
    – jpaugh
    Commented Oct 25, 2018 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.
    Commented Oct 25, 2018 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
    Commented Oct 25, 2018 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
    Commented Oct 25, 2018 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);
    }
2
  • how about response content type and other things u need to fill out to prepare proper response? U sure i can just throw string?
    – NeatNerd
    Commented Feb 21, 2014 at 16:03
  • We need to add content type
    – Faisal
    Commented Jun 6, 2018 at 16:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.