Json.net deserializing nested Dictionaries with non-string key types

c#, dictionary, json, serialization

Solution

The issue is that JSON dictionaries (objects) only support string keys, so Json.Net converts your complex key type to a Json string (calling ToString()) which can't then be deserialized into the complex type again. Instead, you can serialize your dictionary as a collection of key-value pairs by applying the JsonArray attribute.

See this question for details.

Problem

I am using Json.NET to deserialize an object which includes a nested Dictionary with a custom (non-string) key type. Here is a sample of what I am trying to do ``` public interface IInterface { String Name { get; set; } } public class AClass : IInterface { public string Name { get; set; } } public class Container { public Dictionary<IInterface, string> Map { get; set; } public Container() { Map = new Dictionary<IInterface, string>(); } } public static void Main(string[] args) { var container = new Container(); container.Map.Add(new AClass() { Name = "Hello World" }, "Hello Again"); var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects, PreserveReferencesHandling = PreserveReferencesHandling.All, }; string jsonString = JsonConvert.SerializeObject(container, Formatting.Indented, settings); var newContainer = JsonConvert.DeserializeObject<Container>(jsonString); } ``` This yields the exception message: Could not convert string 'ConsoleApplication1.AClass' to dictionary key type 'ConsoleApplication1.IInterface'. Create a TypeConverter to convert from the string to the key type object. Please accept my apology however I cant find a way to de-serialize interface in Dictionary key.

Original source

Related problems