5

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?

Tom
  • 4,007
  • 24
  • 69
  • 105
  • return Json(JsonConvert.SerializeObject(....)); – Stephen Brickner Dec 04 '15 at 14:55
  • 1
    Why do you want to invoke Json.NET explicitly if it will already be called by MVC anyway? Oh wait - Json.NET is the default formatter for ASP.NET WebApi, not ASP.NET MVC. Sorry. See http://stackoverflow.com/questions/14591750/setting-the-default-json-serializer-in-asp-net-mvc – Gary McGill Dec 04 '15 at 15:02

5 Answers5

6

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.

Nicollas Braga
  • 802
  • 7
  • 27
3

You can use ContentResult instead like this:

return Content(JsonConvert.SerializeObject(...), "application/json");
Dygestor
  • 1,259
  • 1
  • 10
  • 20
1
public string GetAccount()
{
    Account account = new Account
    {
        Email = "james@example.com",
        Active = true,
        CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
        Roles = new List<string>
        {
            "User",
            "Admin"
        }
    };

    string json = JsonConvert.SerializeObject(account, Formatting.Indented);

    return json;
}

or

public ActionResult Movies()
{
    var movies = new List<object>();

    movies.Add(new { Title = "Ghostbusters", Genre = "Comedy", Year = 1984 });
    movies.Add(new { Title = "Gone with Wind", Genre = "Drama", Year = 1939 });
    movies.Add(new { Title = "Star Wars", Genre = "Science Fiction", Year = 1977 });

    return Json(movies, JsonRequestBehavior.AllowGet);
}
isxaker
  • 8,446
  • 12
  • 60
  • 87
1

You basically need to write a custom ActionResult that is indicated here in this post

[HttpGet]
public JsonResult GetUsers()
{
    JObject someData = ...;
    return new JSONNetResult(someData);
}

The JSONNetResult function is:

public class JSONNetResult: ActionResult
{
     private readonly JObject _data;
     public JSONNetResult(JObject data)
     {
         _data = data;
     }

     public override void ExecuteResult(ControllerContext context)
     {
         var response = context.HttpContext.Response;
         response.ContentType = "application/json";
         response.Write(_data.ToString(Newtonsoft.Json.Formatting.None));
     }
 }
Community
  • 1
  • 1
dphamcc
  • 17
  • 3
0

You might want to consider using IHttpActionResult since this will give you the benefit of serialization automatically (or you could do it yourself), but also allows you to control the returned error code in case errors, exceptions or other things happen in your function.

    // GET: api/portfolio'
    [HttpGet]
    public IHttpActionResult Get()
    {
        List<string> somethings = DataStore.GetSomeThings();

        //Return list and return ok (HTTP 200)            
        return Ok(somethings);
    }
Wim Van Houts
  • 516
  • 1
  • 8
  • 16