存在問題,其中DateTime/TimeSpan似乎沒有使用JavaScriptSerializer正確反序列化。 當我在反序列化後將對象返回時,TimeSpan爲空,並且如果我使用DateTime,那麼時間都是不合時宜的。 找到這篇文章,但它並沒有真正幫助我太多。 http://www.west-wind.com/weblog/ShowPost.aspx?id=471402JavaScriptSerializer非反序列化DateTime/TimeSpan正確
任何人有任何想法?我應該試試json.net庫嗎?
public class JsonFilter : ActionFilterAttribute
{
public string Param { get; set; }
public Type JsonDataType { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.ContentType.Contains("application/json"))
{
string inputContent;
using (var sr = new StreamReader(filterContext.HttpContext.Request.InputStream))
{
inputContent = sr.ReadToEnd();
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
var result = serializer.Deserialize(inputContent, JsonDataType);
filterContext.ActionParameters[Param] = result;
}
}
}
public class RosterItem
{
public RosterItem()
{
comments = new List<Form.Comment>();
}
public Boolean dirty { get; set; }
public int id { get; set; }
public int staffId { get; set; }
public String description { get; set; }
public int activityId { get; set; }
public DateTime date { get; set; }
public TimeSpan startTime { get; set; }
public TimeSpan endTime { get; set; }
public List<Form.Comment> comments { get; set; }
}
[JsonFilter(Param = "rosterItem", JsonDataType = typeof(RosterItem))]
public int SaveRosterEntry(RosterItem rosterItem)
{
RosterEntry rosterEntry = rosterEntryRepository.GetRosterEntry(rosterItem.id);
if (rosterEntry == null)
{
rosterEntry = new RosterEntry();
rosterEntryRepository.Add(rosterEntry);
}
rosterEntry.ActivityID = rosterItem.activityId;
rosterEntry.StartTime = rosterItem.startTime;
rosterEntry.EndTime = rosterItem.endTime;
rosterEntry.RosterDate = rosterItem.date;
rosterEntry.RosterEmployeeID = rosterItem.staffId;
rosterEntryRepository.Save();
return rosterEntry.RosterEntryID;
}
該解決方案非常適合解決TimeSpan序列化,但我認爲這個問題與DateTime有關。 – 2013-12-09 03:43:56