How can I serialize/deserialize a dictionary with custom keys using Json.Net?

This should do the trick:

Serialization:

JsonConvert.SerializeObject(expected.ToArray(), Formatting.Indented, jsonSerializerSettings);

By calling expected.ToArray() you’re serializing an array of KeyValuePair<MyClass, object> objects rather than the dictionary.

Deserialization:

JsonConvert.DeserializeObject<KeyValuePair<IDataKey, object>[]>(output, jsonSerializerSettings).ToDictionary(kv => kv.Key, kv => kv.Value);

Here you deserialize the array and then retrieve the dictionary with .ToDictionary(...) call.

I’m not sure if the output meets your expectations, but surely it passes the equality assertion.

Leave a Comment