Asp.net-Mvc

MVC4 動作返回 JsonResult 而沒有 null

  • November 9, 2012

我有一個為特定類的對象返回 JsonResult 的操作。我用一些屬性修飾了這個類的屬性以避免空欄位。類定義是:

   private class GanttEvent
   {
       public String name { get; set; }

       [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
       public String desc { get; set; }

       [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
       public List<GanttValue> values { get; set; }
   }

在我的行動中,我使用了一個對象

   var res = new List<GanttEvent>();

我使用以下方法返回:

   return Json(res, JsonRequestBehavior.AllowGet);

不幸的是,我仍然在輸出中收到空值:

   [{"name":"1.1 PREVIOS AL INICIO ","desc":null,"values":null},{"name":"F04-PGA-S10","desc":"Acta preconstrucción","values":null},{"name":"F37-PGA-S10","desc":"Plan de inversión del anticipo","values":null},{"name":"F09-PGA-S10","desc":"Acta de vecindad","values":null},{"name":"F05-PGA-S10","desc":"Acta de inicio","values":null},{"name":"F01-PGA-S10","desc":"Desembolso de anticipo","values":null}]

我錯過了什麼或做錯了什麼?

正如 Brad Christie 所說,MVC4 仍然使用 JavaScriptSerializer,因此為了讓您的對像被 Json.Net 序列化,您必須執行幾個步驟。

首先,從 JsonResult 繼承一個新的類 JsonNetResult 如下(基於 此解決方案):

public class JsonNetResult : JsonResult
{
   public JsonNetResult()
   {
       this.ContentType = "application/json";
   }

   public JsonNetResult(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior jsonRequestBehavior)
   {
       this.ContentEncoding = contentEncoding;
       this.ContentType = !string.IsNullOrWhiteSpace(contentType) ? contentType : "application/json";
       this.Data = data;
       this.JsonRequestBehavior = jsonRequestBehavior;
   }

   public override void ExecuteResult(ControllerContext context)
   {
       if (context == null)
           throw new ArgumentNullException("context");

       var response = context.HttpContext.Response;

       response.ContentType = !String.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

       if (ContentEncoding != null)
           response.ContentEncoding = ContentEncoding;

       if (Data == null)
           return;

       // If you need special handling, you can call another form of SerializeObject below
       var serializedObject = JsonConvert.SerializeObject(Data, Formatting.None);
       response.Write(serializedObject);
   }
}

然後,在您的控制器中,覆蓋 Json 方法以使用新類:

protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
   return new JsonNetResult(data, contentType, contentEncoding, behavior);
}

引用自:https://stackoverflow.com/questions/13294211