duo*_*iha 5 c# serialization json dictionary
我正在使用Json.NET反序列化包含嵌套字典的对象.这是我想要做的一个例子
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);
}
Run Code Online (Sandbox Code Playgroud)
我收到异常消息:无法将字符串'ConsoleApplication1.AClass'转换为字典键类型'ConsoleApplication1.IInterface'.创建TypeConverter以将字符串转换为键类型对象.请接受我的道歉但是我无法找到一种在Dictionary键中反序列化接口的方法.
非常感谢你提前
问题是JSON字典(对象)只支持字符串键,因此Json.Net将您的复杂键类型转换为Json字符串(调用ToString()),然后再将其反序列化为复杂类型.相反,您可以通过应用JsonArray属性将字典序列化为键值对的集合.
有关详情,请参阅此问题.