Extra Action Results

Assembly
WebExtras.Mvc.dll
Namespace
WebExtras.Mvc.Core

JsonNetResult

WebExtras provides a custom JsonResult called JsonNetResult which basically provides JSON return data serialization via the Newtonsoft's Json.NET library. This provides better serialization speed and options.

Markup


  // Let's say we have the following C# class objects that we would like to return as JSON
  public class SomeClass
  {
      public int var1 { get; set; }
      public string var2 { get; set; }          // Notice that this is a nullable type
      public bool var3 { get; set; }
      public double? var4 { get; set; }         // Notice that this is a nullable type
  }

  // Serialize data using Json.NET library
  public JsonNetResult GetJsonNetData()
  {
    SomeClass obj1 = new SomeClass 
    {
      var1 = 99
    };

    return new JsonNetResult(obj1);
  }

  // Serialize data using MVC's native JSON serializer
  public JsonResult GetJsonData()
  {
    SomeClass obj1 = new SomeClass 
    {
      var1 = 99
    };

    return Json(obj1, JsonRequestBehavior.AllowGet);
  }
  

As you can see we have only set one property of the class i.e. var1 to 99. Let us see what the two different action results return

Output


  // Result of GetJsonNetData action
  { "var1": 99, "var3": false }

  // Result of GetJsonData action
  { "var1": 99, "var2": null, "var3": false, "var4": null }
  

The main difference between JsonNetResult and JsonResult is that due to the options provided by the Json.NET library we can selectively ignore null values from an object and choose not to serialize them. This can significantly reduce the amount of JSON payload needed to return especially in case of large C# objects or data sets. This is also useful and actually the recommended way of returning the jQuery Datatable and jQuery Flot binding classes provided by WebExtras since if a JsonResult is used, the unset binding class options automatically get set to null and are returned as such. This can cause problems when creating the said entities i.e. a datatable or a flot chart.