8

I'm using Json.NET to serialize an object that has an IEnumerable of an enum and DateTime. It's something like:

class Chart
{
    // ...
    public IEnumerable<int> YAxis { get; set; }

    public IEnumerable<State> Data { get; set; }

    public IEnumerable<DateTime> XAxis { get; set; }
}

But I need a custom JsonConverter to make the enum serialize as string and to change the DateTime string format.

I've tried using the JsonConverter attribute as mentioned here for enum and a custom IsoDateTimeConverter as done here:

[JsonConverter(typeof(StringEnumConverter))]
public IEnumerable<State> Data { get; set; }

[JsonConverter(typeof(MyDateTimeConverter))]
public IEnumerable<DateTime> XAxis { get; set; }

I was hoping it would work for an IEnumerable too, but unsurprisingly it doesn't:

Unable to cast object of type 'WhereSelectArrayIterator`2[System.Int32,Model.State]' to type 'System.Enum'.

Is there any way to say that the JsonConverterAttribute applies to each item and not on the enumerable itself?

Community
  • 1
  • 1
andrepnh
  • 933
  • 8
  • 21
  • @juharr This was actually an effort to share something that got in my way. And to think I was proud of my googling skills... – andrepnh Apr 12 '16 at 18:18

1 Answers1

10

Turns out that for enumerables you have to use the JsonPropertyAttribute and the ItemConverterType property as follows:

[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public IEnumerable<State> Data { get; set; }

[JsonProperty(ItemConverterType = typeof(MyDateTimeConverter))]
public IEnumerable<DateTime> XAxis { get; set; }

This is mentioned in the documentation as:

To apply a JsonConverter to the items in a collection, use either JsonArrayAttribute, JsonDictionaryAttribute or JsonPropertyAttribute and set the ItemConverterType property to the converter type you want to use.

You might be confused with JsonArrayAttribute, but it cannot target a property.

dbc
  • 104,963
  • 20
  • 228
  • 340
andrepnh
  • 933
  • 8
  • 21