This project has moved. For the latest updates, please go here.

deserializing/serializing List<enum>

May 27, 2010 at 3:32 PM
So, I've got an enum type that looks like: [DwEnumAttribute("blacklist", "class1", "class2", "unaudited")] public enum MyEnum { Blacklist = 0, Class1 = 1, Class2 = 2, Class3 = 3, Unaudited = 4 } The attribute on it allows me to do custom serialization/deserialization - when I declare a class that has one of these enums as a property, I'll do the following: public class SomeClass { [JsonConverter(typeof(GenericEnumConverter)] public MyEnum {get; set;} } and all is well. GenericEnumConverter, which is not shown here, uses reflection at startup to grovel out the string params to build up a Dictionary<Type, DWEnumAttribute>, each DWEnumAttribute has the params value e.g. 'blacklist', 'class1', 'class2', etc. so it can do the right thing. So far, so good. But....unfortunately, my class has a List<T> of these things. the JSON I want to deserialize looks like: // in the middle of MyClassWithList "inv_class_targets": [ "class1", "class2" ] public class MyClassWithList { // what do I do here? public List<MyEnum> InventoryClassList {get; set;} } I'm trying to figure out how to create a JSonConverter object that knows how to serialize/deserialize a List<MyEnum> the input will be a JSon array "class2", "class3", and I want to end up with a List<MyEnum>, and vice-versa: I want to go // outbound MyClassWithList obj = new MyClassWithList() {InventoryClassList = {MyEnum.Class2, MyEnum.Blacklist}; string json = JsonConvert.Serialize(obj, Formatting.None, new JsonSerializerSettings() {etc.}}); //inbound String response = CallTheServer(); JToken jtoken = response["response"]["myclasswithlist"]; MyClassWithList obj = JsonConvert.DeserializeObject<MyClassWithList>(jtoken); This sort of approach works fine when the object just contains properties that are either single enums, or subobjects that themselves have appropriate property attribute decorations (JsonProperty and JsonConverter). I'm unable to decorate the declaration of MyEnum itself with a [JsonConverter(typeof(GenericEnumConverter)] because it's an enum. Any ideas?
May 27, 2010 at 10:30 PM

I checked in a change yesterday that will allow a JsonConverter attribute to be placed on an enum.