6

I have this Json from a web api:

jsonstring ={"users":[{"id":1123,"last_update":"2016-02-28 14:53:04"}],"page":1,"pages":1}

which I want to deserialize in an object like:

public class Rootobject
{
    public User[] users { get; set; }
    public int page { get; set; }
    public int pages { get; set; }
}

public class User
{
    public int id { get; set; }
    public DateTime last_update { get; set; }
}

for this I use:

 var obj= JsonConvert.DeserializeObject<Rootobject>(jsonString);

the result has null for last_update.

jsonstring is a string result from WebClient.DownloadString(url); which look like above example.

How can I get the date on deserialization?

Edit:

None of the solutions from this post Deserializing dates with dd/mm/yyyy format using Json.Net help me fix my issue.

Community
  • 1
  • 1
Lucian Bumb
  • 2,719
  • 5
  • 25
  • 37

3 Answers3

6
var obj = JsonConvert.DeserializeObject<Rootobject>(jsonString, 
            new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });

Fiddle

Adrian Iftode
  • 15,175
  • 3
  • 44
  • 71
0

Change the property last_update as Nullable, Then it allows you to assign the null literal to the DateTime type. It provides another level of indirection. So use like the following:

public DateTime? last_update { get; set; }

This is for accepting The date even if it is null, you can specify the Date format While Deserializing the JSON. Use this Thread for that

Community
  • 1
  • 1
sujith karivelil
  • 27,818
  • 6
  • 51
  • 82
-1

"2016-02-28 14:53:04" is not a valid RFC3339 date time, and I think it can't parse it because of that.

It has to be:

2016-02-28T14:53:04

Also note that the can't be null, since DateTime is a struct. To make it nullable, make the data type DateTime? which does allow null values.

Patrick Hofman
  • 148,824
  • 21
  • 237
  • 306