Deserializing Dates with Dd/Mm/Yyyy Format Using JSON.Net

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

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.

JsonConvert.DeserializeObject with two types of datetime format

You don't need to specify any converter at all. By default, both of those formats will work.

class Foo
{
public DateTime DateTime { get; set; }
}

// This Just Works.

string json1 = "{ \"DateTime\" : \"12/31/2017\" }";
string json2 = "{ \"DateTime\" : \"12/31/2017 23:59:59\" }";

var o1 = JsonConvert.DeserializeObject<Foo>(json1);
var o2 = JsonConvert.DeserializeObject<Foo>(json2);

How to deserialize object with date in C#

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

Fiddle



Related Topics



Leave a reply



Submit