json.net: specify converter for dictionary keys

Viewed 10295

I have a JSON:

{ 
    "data": { "A": 5, "B": 6 }, 
    "foo": "foo", 
    "bar": "bar" 
}

I need to deserialize data into a class:

public Dictionary<MyEnum, int> Data { get; set; }
public string Foo { get; set; }
public string Bar { get; set; }

But MyEnum values are CodeA, and CodeB instead of simply A and B respectively.

I have a custom Converter that can handle conversion. But how do I specify a JsonConverter to use with Dictionary keys?

3 Answers

I couldn't get any TypeConverter solution working and didn't want to have a JsonConverter that builds a string-key dictionary and then copies everything into a new dictionary, so I went with something like this:

public sealed class MyEnumKeyDictionary<TValue> : IReadOnlyDictionary<MyEnum, TValue>, IDictionary<string, TValue>
{
    private readonly Dictionary<MyEnum, TValue> actual = new Dictionary<MyEnum, TValue>();

    // implement IReadOnlyDictionary implicitly, passing everything from `actual`

    // implement IDictionary explicitly, passing everything into/from `actual` after doing Enum.Parse/Enum.ToString
}
Related