7

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,821
  • 5
  • 26
  • 39

3 Answers3

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

Fiddle

Adrian Iftode
  • 15,465
  • 4
  • 48
  • 73
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
  • 28,671
  • 6
  • 55
  • 88
-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
  • 153,850
  • 22
  • 249
  • 325