Search code examples
c#json.netjson-deserialization

Deserialize JSON string having multiple datetime formats to c# object


This is what the JSON response is:

{
  "data": [
    {
      "someTicketNumber": "123456",
      "callInDateTimeUtc": "2020-09-09T20:16:26Z",
      "lastUpdatedDateTimeUtc": "2020-09-09T20:28:11Z",
      "availableDateLocalToSomeplace": "2020-09-10",
      "availableTimeLocalToSomeplace": "T10:30:00Z"
    }
  ]
}

Actual Result of JsonConvert.DeserializeObject<T>(json):

availableDateLocalToSomeplace availableTimeLocalToSomeplace
9/10/2020 12:00:00 AM 9/11/2020 10:30:00 AM

My expected result:

availableDateLocalToSomeplace availableTimeLocalToSomeplace
9/10/2020 10:30:00 AM

I can't put a generic converter settings like this:

JsonConvert.DeserializeObject<T>(json, new 
JsonSerializerSettings
{
    DateFormatString = "yyyy-MM-dd" OR "THH:mm:ssZ"
});

because I need 2 different date time format types. How do I accomplish this?


Solution

  • In this case you can do like this: Create a CustomDateTimeConverter class, and pass the format to it's constructor, like so

    public class DateFormatConverter : IsoDateTimeConverter
    {
        public DateFormatConverter(string format)
        {
            DateTimeFormat = format;
        }
    }
    

    In the c# class,

    public partial class Tickets
    {
        [JsonProperty("data")]
        public TicketProps[] Data { get; set; }
    }
    
    public partial class TicketProps
    {
        [JsonProperty("someTicketNumber")]
        public string SomeTicketNumber { get; set; }
    
        [JsonProperty("callInDateTimeUtc")]
        [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-ddTHH:mm:ssZ")]
        public DateTime? CallInDateTimeUtc { get; set; }
    
        [JsonProperty("lastUpdatedDateTimeUtc")]
        [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-ddTHH:mm:ssZ")]
        public DateTime? LastUpdatedDateTimeUtc { get; set; }
    
        [JsonProperty("availableDateLocalToSomeplace")]
        [JsonConverter(typeof(DateFormatConverter), "yyyy-MM-dd")]
        public DateTime?AvailableDateLocalToSomeplace { get; set; }
    
        [JsonProperty("availableTimeLocalToSomeplace")]
        [JsonConverter(typeof(DateFormatConverter), "THH:mm:ssZ")]
        public DateTime? AvailableTimeLocalToSomeplace { get; set; }
    }
    

    Now your simple JsonConvert.DeserializeObject<T>(json) will work just fine.