我有一个课程如下:
public class ViewItem { [DataMember(Name = "title")] public string Title { get; set; } [DataMember(Name = "created_at")] public string CreatedAt { get; set; } }当我尝试将json字符串反序列化为object时,我永远无法获得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);我已经阅读了这篇文章,并尝试提供不同的json转换以及日期解析处理,但它不起作用。
更新:
我已经尝试过CreatedAt属性作为DateTime,DateTime? 和DateTimeOffset以及简单的字符串。
I have a class as following:
public class ViewItem { [DataMember(Name = "title")] public string Title { get; set; } [DataMember(Name = "created_at")] public string CreatedAt { get; set; } }When I try to deserialize json string to object, I never get value for CreatedAt field. My json string is as follows:
[ { "created_at" : "2014-03-05T10:26:12Z" , "title" : "task 4" } , { "created_at" : "2014-03-05T10:26:12Z" , "title" : "task 5" } ]The deserialization code is as follows:
JsonConvert.DeserializeObject<List<ViewItem>>(json);I have read this article and tried to supply different json convert as well date parse handling but it did not work.
Update:
I have tried CreatedAt property as DateTime, DateTime? and DateTimeOffset as well as simple string.
最满意答案
尝试将[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 AMTry adding [DataContract] to your class declaration. Also change the type of the CreatedAt property from string to DateTime:
[DataContract] public class ViewItem { [DataMember(Name = "title")] public string Title { get; set; } [DataMember(Name = "created_at")] public DateTime CreatedAt { get; set; } }With these changes (and the fix to the JSON), it works for me:
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); }Output:
Title: task 4 CreatedAt: 3/5/2014 10:26:12 AM Title: task 5 CreatedAt: 3/5/2014 10:26:12 AM更多推荐
发布评论