I am using Json.NET to deserialized an object which included a nested Dictionary. 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);
}
I received 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.
Thank you very much in advance
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With