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?

1
  • @juharr This was actually an effort to share something that got in my way. And to think I was proud of my googling skills... Commented Apr 12, 2016 at 18:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.