0

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?

elloco999
  • 80
  • 7

1 Answers1

1

use [JsonProperty(ItemConverterType = typeof(MyDateTimeConverter))]

Orange
  • 31
  • 4
  • Please check this post https://stackoverflow.com/questions/36580519/custom-json-serialization-for-each-item-in-ienumerable?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Orange May 12 '18 at 02:34