2014-02-21 110 views
0

我有以下的接口和類結構JSON序列化繼承列表類屬性不會被序列

public class RefreshCostResult : IRefreshCostResults 
    { 
     #region IRefreshCostResults Members 

     public TimeSpan TimeToCompletion 
     { 
      get; 
      set; 
     } 

     public string ApplicationLocation 
     { 
      get; 
      set; 
     } 

     public Enums.RefreshCostStatus ApplicationResult 
     { 
      get; 
      set; 
     } 

     #endregion 
    } 

    public class RefreshCostItems : List<IRefreshCostResults>, IRefreshCostItems 
    { 
     public TimeSpan TotalTimeTaken 
     { 
      get 
      { 
       var tsTotal = (from x in this 
           select x.TimeToCompletion).Sum(x => x.TotalMilliseconds); 
       return TimeSpan.FromMilliseconds(tsTotal); 
      } 
     } 
    } 

,並在我的控制器動作我正在通過下面的函數返回一個JSON字符串

[HttpPost] 
public JsonResult RefreshCostOnProject(int projectID, int userId) 
{ 
    var result = new RefreshCostItems(); 
    result.Add(new RefreshCostResult 
    { 
     ApplicationLocation = "FOO", 
     TimeToCompletion = TimeSpan.FromMinutes(22), 
     ApplicationResult = RefreshCostStatus.Success 
    }); 
    return Json(result, JsonRequestBehavior.DenyGet); 
} 

但是,當我調用該函數,並返回結果012xx未被序列化。 返回的JSON是

[{ 
     "TimeToCompletion" : { 
      "Hours" : 0, 
      "Minutes" : 22, 
      "Seconds" : 0, 
      "Milliseconds" : 0, 
      "Ticks" : 13200000000, 
      "Days" : 0, 
      "TotalDays" : 0.015277777777777777, 
      "TotalHours" : 0.36666666666666664, 
      "TotalMilliseconds" : 1320000, 
      "TotalMinutes" : 22, 
      "TotalSeconds" : 1320 
     }, 
     "ApplicationLocation" : "FOO", 
     "ApplicationResult" : 1 
    } 
] 

有什麼我失蹤了嗎?我附加了一個調試器,並且該屬性不會在序列化中調用。

+0

你知道那命名空間不必是完全合格的?特別是在SO問題的示例代碼中,它變成了純粹的噪聲。 – Athari

回答

1

不要從List<T>繼承。 JSON序列化器將集合序列化爲JSON數組。根據定義,數組不能具有屬性。

與封裝替換繼承:

class RefreshCostItems 
{ 
    public List<RefreshCostResult> Items { ... } 
    public TimeSpan TotalTimeTaken { ... } 
} 
+0

非常感謝。這很有魅力。 – Qpirate