Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deserialize JSON Date to C# Object with DateTime Returning 01/01/0001

I’m using Newtonsoft to translate a JSON string that presents a date

"[{\"Name\":\"Learning\",\"Start Date\":\"2022-03-01\",\"End Date\":\"2022-04-30\"]"

And I want to deserialize it to this custom object

public class MyObject
{
    public string Name { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

By doing this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var myObject = JsonConvert.DeserializeObject<List<MyObject>>(jsonRecords,
            new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" });

But the StartDate and EndDate objects are always coming out as 01/01/0001, while I’d want them to show in this format: dd/MM/yyyy

I also tried to use new IsoDateTimeConverter { DateTimeFormat = "dd/MM/yyyy" } but that didn’t work either (and I think you need to use the format in which the date is coming from json?)

What am I doing wrong?

>Solution :

Add [JsonProperty("Start Date")] above public DateTime StartDate { get; set; } and similar above public DateTime EndDate { get; set; }:

public class MyObject
{
    public string Name { get; set; }
    [JsonProperty("Start Date")]
    public DateTime StartDate { get; set; }
    [JsonProperty("End Date")]
    public DateTime EndDate { get; set; }
}

The problem was that json property names (‘Start Date’) and class property names (‘StartDate’) were not the same so it defaulted to 01/01/0001.

This will work without the need for IsoDateTimeConverter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading