Search code examples
c#json.netjson-deserialization

Deserializing yyyyMMddTHHmmssZ DateTime format using JsonConvert.DeserializeObject


I have a JSON with DateTime field which I deserialize using JsonConvert.DeserializeObject, and it is working as expected except when I use yyyyMMddTHHmmssZ DateTime format which is one of the ISO8601 formats.

According to the documentation of IsoDateTimeConverter:

Converts a to and from the ISO 8601 date format (e.g. "2008-04-12T12:53Z").

So why this code:

var serializeSettings=new JsonSerializerSettings();
serializeSettings.Converters.Add(new IsoDateTimeConverter());
var result= JsonConvert.DeserializeObject<EmployementHistory>(json,serializeSettings);

is throwing the following exception:

{System.FormatException: String was not recognized as a valid DateTime. at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at Newtonsoft.Json.Converters.IsoDateTimeConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)

My Model:

public class EmployementHistory
{
    public string EmployeeName { get; set; }
    public DateTime PositionChangeDate { get; set; }
}

Json Example:

{ "employeename":"Tom", "PositionChangeDate":"20180710T135034Z" }


Solution

  • According to official documentation, the IsoDateTimeConverter has a public property called DateTimeFormat where you can set your own format -
    so all you need to do is supply that format:

    var serializeSettings=new JsonSerializerSettings();
    serializeSettings.Converters.Add(new IsoDateTimeConverter() {DateTimeFormat = "yyyyMMddTHHmmssZ"});
    var result= JsonConvert.DeserializeObject<MyClass>(json,serializeSettings);