I'm working on a WebApi 2 service that returns data in JSON format. I use two formats for DateTimes, date: "2017-01-31" and datetime: "2017-01-31T12:00:00.000Z". The datetime format is used the most so I've set this as the default in the global.asax:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'" });
And I use a JsonConverter attribute using a custom IsoDateTimeConverter on those DateTime fields that need to be formatted as date:
public class Foo
{
[JsonConverter(typeof(OnlyDateConverter))]
public DateTime Bar { get; set; }
}
public class OnlyDateConverter : IsoDateTimeConverter
{
public OnlyDateConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
}
So far all is fine, this works like a charm.
But here's the problem: For some objects I have a list of DateTime objects that need to be formatted as date. But the JSON converter seems to not support using a JsonConverter attribute on a list.
public class Foo
{
[JsonConverter(typeof(OnlyDateConverter))] // This works
public DateTime Bar { get; set; }
[JsonConverter(typeof(OnlyDateConverter))] // This does not work!
public List<DateTime> Bars { get; set; }
}
This results in the following error: Unexpected value when converting date. Expected DateTime or DateTimeOffset, got System.Collections.Generic.List`1[System.DateTime].
Pretty clear, you can't use [JsonConverter(typeof(OnlyDateConverter))] on a list of dates. But then how do I format a list of DateTime as date?
I've been searching for a solution but can't seem to find anything other than creating a class that consists of just one DateTime property with the attribute. But that just doesn't seem right to me.
Surely there must be a way to use the JsonConverter attribute on a list of DateTimes? What am I missing here?