Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize object with date in C# [duplicate]

Tags:

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.

like image 642
Lucian Bumb Avatar asked Jun 16 '16 14:06

Lucian Bumb


People also ask

How do I deserialize a date in C#?

for this I use: var obj= JsonConvert. DeserializeObject<Rootobject>(jsonString); the result has null for last_update .

How to deserialize a JSON in c#?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.


1 Answers

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

Fiddle

like image 68
Adrian Iftode Avatar answered Sep 28 '22 03:09

Adrian Iftode