C#-反序列化ISO 8601日期
作者:互联网
我有一个如下课程:
public class ViewItem
{
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "created_at")]
public string CreatedAt { get; set; }
}
当我尝试将json字符串反序列化为对象时,我从没有获得CreatedAt字段的值.我的json字符串如下:
[ { "created_at" : "2014-03-05T10:26:12Z" ,
"title" : "task 4"
} ,
{ "created_at" : "2014-03-05T10:26:12Z" ,
"title" : "task 5"
}
]
反序列化代码如下:
JsonConvert.DeserializeObject<List<ViewItem>>(json);
我已经阅读了this article,并尝试提供不同的json转换以及日期解析处理,但是它不起作用.
更新:
我已经尝试过将CreatedAt属性设置为DateTime,DateTime吗?和DateTimeOffset以及简单的字符串.
解决方法:
尝试将[DataContract]添加到类声明中.还将CreatedAt属性的类型从字符串更改为DateTime:
[DataContract]
public class ViewItem
{
[DataMember(Name = "title")]
public string Title { get; set; }
[DataMember(Name = "created_at")]
public DateTime CreatedAt { get; set; }
}
经过这些更改(以及JSON修复),它对我有用:
string json = @"[{""created_at"":""2014-03-05T10:26:12Z"",""title"":""task 4""},{""created_at"":""2014-03-05T10:26:12Z"",""title"":""task 5""}]";
List<ViewItem> list = JsonConvert.DeserializeObject<List<ViewItem>>(json);
foreach (ViewItem item in list)
{
Console.WriteLine("Title: " + item.Title);
Console.WriteLine("CreatedAt: " + item.CreatedAt);
}
输出:
Title: task 4
CreatedAt: 3/5/2014 10:26:12 AM
Title: task 5
CreatedAt: 3/5/2014 10:26:12 AM
标签:json-net,iso8601,datetime,json,c 来源: https://codeday.me/bug/20191029/1962380.html