Update: In the 7.x release of Json.NET, a DictionaryKeyResolver was added that might be able to fix this problem too. I haven’t used it yet, so I can’t really say, but you might want to check it out.

JSON.NET is a great tool and it already handles Dictionaries well, unless your keys are classes (as opposed to structs). Say you have the following class you want to serialize:

public class DataPoints
{
    public IDictionary<DataPointKey, int> Values { get; set; }
}

And the DataPointKey class:

public class DataPointKey
{
    public int Length { get; set; }
    public int Height { get; set; }
}

I’m just making stuff up here, don’t mind the actual contents of the class. The important thing is that the key of our Dictionary is a class.

When you let JSON.NET serialize this, you will get the following:

{"Values":{"JsonDictionary.DataPointKey":200}}

Notice how the key is just the class name. This will not deserialize nicely.

In the past, I would create a custom JsonConverter, but this meant repeating code over and over when new keys were introduced. Inheriting from a base converter was my first solution, but I’ve finally found a converter that can handle any Type.

The result is a little more verbose, but serializes and deserializes nicely:

{"Values":[{"Key":{"Length":10,"Height":20},"Value":200}]}}

The entire code is a little too long to post here, but I’ve made [a Gist](https://gist.github.com/petermorlion/c92e3af4ecf256d4b66c) you can check out.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.