Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.net deserialized nested Dictionary

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

like image 633
duongthaiha Avatar asked Jan 28 '14 00:01

duongthaiha


1 Answers

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.

like image 84
ChaseMedallion Avatar answered Oct 14 '22 00:10

ChaseMedallion