Reputation: 2078
I have the following Interface and class structure
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);
}
}
}
and in my controller action i am returning a JSON string via the following function
[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);
}
But when I call the function and the result is returned the Property TotalTimeTaken
is not serialised.
the returned JSON is
[{
"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
}
]
Is there something I am missing? I have attached a debugger and the property is not getting called on serialisation.
Upvotes: 0
Views: 157
Reputation: 34285
Do not inherit from List<T>
. JSON serializers serialize collections as JSON arrays. And arrays can't have properties by definition.
Replace inheritance with encapsulation:
class RefreshCostItems
{
public List<RefreshCostResult> Items { ... }
public TimeSpan TotalTimeTaken { ... }
}
Upvotes: 1