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. 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" );
Sign up to request clarification or add additional context in comments.

5 Comments

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
This looks like a more robust way of handling it. Plus, you don't have to change your types from JsonResult to ActionResult.
@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.
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.)
My second statement was referring to the result type of the expression, which is ContentResult for the above; whereas I was already using JsonResult.
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 Comments

how about response content type and other things u need to fill out to prepare proper response? U sure i can just throw string?
We need to add content type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.