2012-11-08 81 views
8

我有一個行動,返回一個特定類的對象的JsonResult。我用一些attrib裝飾了這個類的屬性以避免空字段。類定義是:MVC4行動返回JsonResult沒有null

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}] 

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

回答

6

正如Brad Christie所說,MVC4劇照仍然使用JavaScriptSerializer,所以爲了讓你的對象由Json.Net序列化,你需要執行幾個步驟。

首先,繼承JsonResult一個新的類JsonNetResult如下(根據this solution):

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); 
} 
+0

不知道這個答案是否仍然相關,但我需要這樣的東西,並且做了一個c/p的代碼。不幸的是,它沒有按預期工作,但我編輯了你的JsonNetResult類稍微:var serializedObject = JsonConvert.SerializeObject(Data,Formatting.None,new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}); ...現在它完美地工作。謝謝! – robertpaulsen

0

我的建議是看看會發生什麼,如果你只是將一個GanttEvent對象序列化爲JSON。同時檢查你對Json的呼叫是否合適。