Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP MVC 5 and Json.NET: action return type

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?

like image 879
Tom Avatar asked Dec 04 '15 14:12

Tom


2 Answers

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.

like image 62
Nicollas Braga Avatar answered Sep 27 '22 21:09

Nicollas Braga


You can use ContentResult instead like this:

return Content(JsonConvert.SerializeObject(...), "application/json");
like image 40
Dygestor Avatar answered Sep 27 '22 20:09

Dygestor