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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With