我有一个类如下:
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
属性的类型从 string
更改为 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
关于c# - 反序列化 iso 8601 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22517225/