在我的 ASP.Net MVC 项目中,使用 NewtonSoft json 反序列化器,我使用一个 json Web 服务以/Date()/格式发送日期。我收到的 json 为(显示许多数组元素中的第一个):
[
{
"Prop1": false,
"Prop2": false,
"TimeDtlList": [
{
"CustName": null,
"tranDate": null,
"startTime": "/Date(1490721584000-0500)/",
"endTime": "/Date(1490734813000-0500)/",
}
],
"name": "Bill, Jack F.",
}
]
在我的代码中,我使用 DateFormatHandling.MicrosoftDateFormat
,但是我仍然收到错误:
Could not convert string to decimal: /Date(1490721584000-0500)/. Path '[0].times[0].startTime', line 1, position 337.
我正在使用以下方法反序列化对象:
JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings{DateFormatHandling = DateFormatHandling.MicrosoftDateFormat};
List<Times> timesList = JsonConvert.DeserializeObject <List<Times>>(text, microsoftDateFormatSettings);
我的模型类定义为:
public class Times
{
public Boolean prop1 { get; set; }
public Boolean prop2 { get; set; }
public List<TimeDtl> TimeDtlList { get; set; }
public String name { get; set; }
}
public class TimeDtl
{
public String CustName { get; set; }
public DateTime? tranDate { get; set; }
public Decimal? startTime { get; set; }
public Decimal? endTime { get; set; }
}
如何正确反序列化时间?
最佳答案
根据您的json
它只是 Times
的对象不是List<Times>
string json = "{\"startTime\": \"/Date(1490721584000-0500)/\",\r\n\"endTime\": \"/Date(1490734813000-0500)/\"}";
dynamic stuff = JsonConvert.DeserializeObject(json);
Times result = stuff.ToObject<Times>();
您可以访问诸如
之类的值 result.startTime
用于 ToObject
的文档你可以检查这个ToObject
编辑
所以根据你的新模型 json 应该是
var result = stuff.ToObject<List<Times>>();
并且在您的模型中,您需要更正类型
public Decimal? startTime { get; set; }
public Decimal? endTime { get; set; }
至
public DateTime? startTime { get; set; }
public DateTime? endTime { get; set; }
自 startTime
和endTime
类型为DateTime
关于json - NewtonSoft Json 反序列化错误 - 无法将字符串转换为十进制 :/Date(1490721584000-0500)/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43144178/