JSON序列化继承列表类属性未序列化

时间:2014-02-21 11:40:12

标签: c# json serialization

我有以下接口和类结构

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

但是当我调用该函数并返回结果时,属性TotalTimeTaken未被序列化。 返回的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
    }
]

我有什么遗失的吗?我附加了一个调试器,并且没有在序列化时调用该属性。

1 个答案:

答案 0 :(得分:1)

不要继承List<T>。 JSON序列化程序将集合序列化为JSON数组。根据定义,数组不能具有属性。

将继承替换为封装:

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