Json.Net And ActionResult
44,916
Solution 1
You should just be able to do this in your action method:
return Content( res.ToString(), "application/json" );
Solution 2
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);
}
Related videos on Youtube
Author by
NeatNerd
My mission is to make sure that the smartest minds get the toughest challenges and are empowered to overcome them
Updated on August 03, 2022Comments
-
NeatNerd almost 2 years
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); //??????? }
-
user692942 over 6 years@Liam this question came first so how can it be a duplicate? You've flagged the wrong question.
-
-
NeatNerd about 10 yearshow about response content type and other things u need to fill out to prepare proper response? U sure i can just throw string?
-
Faisal almost 6 yearsI 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 almost 6 yearsWe need to add content type
-
jpaugh over 5 yearsThis looks like a more robust way of handling it. Plus, you don't have to change your types from
JsonResult
toActionResult
. -
Craig W. over 5 years@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.
-
jpaugh over 5 yearsThere 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 over 5 yearsMy second statement was referring to the result type of the expression, which is
ContentResult
for the above; whereas I was already usingJsonResult
.