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
Pass Complex Parameters to [Theory]
Why Are Unsigned Int's Not Cls Compliant
Why Use Icollection and Not Ienumerable or List<T> on Many-Many/One-Many Relationships
How to Mock Out the File System in C# for Unit Testing
Get the Titles of All Open Windows
How to Access Backing Fields Behind Auto-Implemented Properties
How to Convert a Decimal to a Double in C#
How to Implement Ienumerable<T>
Why Always Close Database Connection
How to Convert Unicode Escape Sequences to Unicode Characters in a .Net String
Is There a Downside to Adding an Anonymous Empty Delegate on Event Declaration
Generic Constraints, Where T:Struct and Where T:Class
Metadata File '.Dll' Could Not Be Found
How to Call Base.Base.Method()
Is There Any Benefit of Using an Object Initializer