Question

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.

Was it helpful?

Solution

Try 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

OTHER TIPS

You are using DataMemberAttribute which is from System.Runtime.Serialization. but JsonConvert from Newtonsoft.Json to deserialize.

Use:

[JsonProperty("title")]

Instead of:

[DataMember(Name = "title")]
DateTime dateProperty=Convert.ToDateTime(DateTime)

will yield

"dateProperty":"/Date(1343966400000-0400)/"

Whereas:

string dateProperty=Convert.ToString(DateTime)

will yield

"dateProperty":"8/3/2012 6:20:43 PM"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top