JsonConverterAttribute for collection items

Feb 24, 2012 at 10:36 PM

I'd like to use IsoDateTimeConverter on a collection of datetimes without it being automatically used by all datetimes in the serialization (e.g. I can't add it to JsonSerializer.Converters). What is the best way to accomplish this? This doesn't work, but something like it would be ideal:

class Widget
{
  [JsonConverter(typeof(IsoDateTimeConverter))]
  public DateTime[] DateTimes { get; set; }
}

Mar 1, 2012 at 11:26 PM

Patch 11619 uploaded. With the patch, the example above would be written like this:

class Widget
{
  [JsonConverter(ContainerItemConverterType = typeof(IsoDateTimeConverter))]
  public DateTime[] DateTimes { get; set; }
}

Mar 3, 2012 at 6:30 PM
Edited Mar 3, 2012 at 6:31 PM

I'm not married to the API as submitted. Another possibility:

[JsonConverter(typeof(IsoDateTimeConverter), Usage=CollectionItem)]
...
enum JsonConverterUsage
{
  Normal,
  CollectionItem,
  DictionaryValue
}

or maybe just a Boolean:

[JsonConverter(typeof(IsoDateTimeConverter), UsedByItems=true)]
Mar 3, 2012 at 8:10 PM

Patch 11637 uploaded, which uses the UsedByItems API.

It occurs to me that the new property doesn't work when JsonConverterAttribute is used on a type. That code is less clear to me, but that usage should probably either work properly or fail with an exception.

  // doesn't work
  [JsonConverter(typeof(WidgetAsIdJsonConverter), UsedByItems = true)]
  public class WidgetCollection : Collection<Widget>
  {
  }


May 9, 2012 at 5:58 PM

The latest releases of Json.NET support ItemConverterType on JsonConverterAttribute. Thanks!