i'm using ASP MVC 5. I have an action in a controller that return a json object:
[HttpGet]
public JsonResult GetUsers()
{
return Json(....., JsonRequestBehavior.AllowGet);
}
Now i want to use the JSON.Net library and i see that in ASP MVC 5 is yet present. In effect i can write
using Newtonsoft.Json;
without import the library from NuGet.
Now i've tried to write:
public JsonResult GetUsers()
{
return JsonConvert.SerializeObject(....);
}
But i have an error during compilation: I cann't convert the return type string to JsonResult. How can i use the Json.NET inside an action? What is the correct return type of an action?
I'd prefer to create an object
extension that results in a custom ActionResult
as it can be applied inline to any object when returning it
The bellow extension make use of Newtonsoft Nuget to serialize objects ignoring null properties
public static class NewtonsoftJsonExtensions
{
public static ActionResult ToJsonResult(this object obj)
{
var content = new ContentResult();
content.Content = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
content.ContentType = "application/json";
return content;
}
}
The bellow example demonstrate how to use the extension.
public ActionResult someRoute()
{
//Create any type of object and populate
var myReturnObj = someObj;
return myReturnObj.ToJsonResult();
}
Enjoy.
You can use ContentResult
instead like this:
return Content(JsonConvert.SerializeObject(...), "application/json");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With