Bob*_*orn 15 javascript c# json stringify
我有一个javascript函数,用JSON数据调用MVC控制器:
var specsAsJson = JSON.stringify(specs);
$.post('/Home/Save', { jsonData: specsAsJson });
Run Code Online (Sandbox Code Playgroud)
在服务器端,在控制器内,我似乎无法通过此错误:
/ Date(1347992529530)/不是DateTime的有效值.
当我调用Deserialize()(下面的方法中的第三行)时会发生异常:
public ActionResult Save(string jsonData)
{
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new TimeSpanJsonConverter() });
var specs = serializer.Deserialize<List<EquipmentSpecWithParameterlessConstructor>>(jsonData);
return View("Index", _allTrackerJobs);
}
Run Code Online (Sandbox Code Playgroud)
我一直在做一些谷歌搜索,上面的代码是我最近尝试使这项工作(从这里使用TimeSpanJsonConverter ).其他方法显示只向服务器发送日期,但我有一个对象列表,其中日期作为一些属性.
是否有一种优雅的,普遍接受的方法来解决这个问题,还是我们还需要某种丑陋的解决方法?解决这个问题的正确方法是什么?
===================原始问题结束===================
编辑 - 通过使用JsonConvert序列化解决
请参阅下面的答案(不是这个问题中糟糕的解决方法).
编辑 - 糟糕的解决方法
我创建了一个DTO,其字段与域对象完全相同,只是我将日期字段设置为字符串,以便反序列化.现在我可以反序列化它,我将努力将日期转换为有效的格式,以便我可以从我的DTO创建域对象.
public class EquipmentSpecDto
{
public string StartTime { get; set; }
public string EndTime { get; set; }
// more properties here
}
Run Code Online (Sandbox Code Playgroud)
我只是使用DTO进行反序列化:
var specs = serializer.Deserialize<List<EquipmentSpecDto>>(jsonData);
Run Code Online (Sandbox Code Playgroud)
编辑2 - 将JavaScript日期转换为.NET
为了完整性,并希望我一个小时保存其他人,这就是我能够转换javascript日期的方式:
foreach (EquipmentSpecDto specDto in specDtos)
{
// JavaScript uses the unix epoch of 1/1/1970. Note, it's important to call ToLocalTime()
// after doing the time conversion, otherwise we'd have to deal with daylight savings hooey.
DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
Double startMilliseconds = Convert.ToDouble(specDto.StartTime.Substring(6, 13));
Double endMilliseconds = Convert.ToDouble(specDto.EndTime.Substring(6, 13));
DateTime startTime = unixEpoch.AddMilliseconds(startMilliseconds).ToLocalTime();
DateTime endTime = unixEpoch.AddMilliseconds(endMilliseconds).ToLocalTime();
EquipmentSpec spec = new EquipmentSpec(startTime, endTime, specDto.Equipment);
specs.Add(spec);
}
Run Code Online (Sandbox Code Playgroud)
Bob*_*orn 13
我找到了一个简单的答案.在我的javascript中,我使用JavaScriptSerializer序列化数据.经过大量的谷歌搜索后,我发现这篇文章展示了如何使用JsonConvert进行序列化,这会导致使用更友好的DateTime.
旧:
var specs = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.JobSpecEquipment))
Run Code Online (Sandbox Code Playgroud)
日期看起来像这样: Date(1348017917565)
新:
var specs = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.JobSpecEquipment));
Run Code Online (Sandbox Code Playgroud)
日期看起来像这样: 2012-09-18T21:27:31.1285861-04:00
所以问题实际上是我在第一时间序列化的方式.一旦我使用JsonConvert,后端的反序列化就可以了.
我在互联网上找到了这段代码.它对我来说就像一个魅力......
function customJSONstringify(obj) {
return JSON.stringify(obj).replace(/\/Date/g, "\\\/Date").replace(/\)\//g, "\)\\\/")
}
Run Code Online (Sandbox Code Playgroud)