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
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.