Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom json serialization for each item in IEnumerable [duplicate]

Tags:

json

c#

json.net

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?

like image 325
andrepnh Avatar asked Apr 12 '16 17:04

andrepnh


1 Answers

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.

like image 98
andrepnh Avatar answered Oct 18 '22 03:10

andrepnh