Json.net反序列化嵌套字典 [英] Json.net deserialized nested Dictionary

查看:252
本文介绍了Json.net反序列化嵌套字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Json.NET反序列化一个包含嵌套字典的对象。这是我正在尝试做的一个例子

  public interface IInterface 
{
String Name {得到;组;
}

public class AClass:IInterface
{
public string Name {get;组; }
}

public class Container
{
public Dictionary< IInterface,string>地图{get;组; }
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);
}

我收到异常消息:无法将字符串ConsoleApplication1.AClass转换为字典键类型ConsoleApplication1.IInterface。创建一个TypeConverter以将其从字符串转换为键类型对象。请接受我的道歉,但是我不能找到一种在字典密钥中解除序列化接口的方法。



提前非常感谢你



请参阅这个问题详细。


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.

这篇关于Json.net反序列化嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆