IConvertible
接口的项目,使我能够将任何基本类型添加到字典中。 var dic = new Dictionary<string, IConvertible>();
dic.Add("bool2", false);
dic.Add("int2", 235);
dic.Add("string2", "hellohello");
我使用Json.net实现了以下序列化列表的功能:
var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Objects;
var dicString = JsonConvert.SerializeObject(dic, Newtonsoft.Json.Formatting.Indented, settings);
这给了我以下输出:
{
"$type": "System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.IConvertible, mscorlib]], mscorlib",
"bool2": false,
"int2": 235,
"string2": "hellohello"
}
然而,当尝试进行这样的反序列化时:
var dic2 = JsonConvert.DeserializeObject<Dictionary<string, IConvertible>>(dicString);
...我得到了以下错误:
Error converting value False to type 'System.IConvertible'. Path 'bool2', line 3, position 16.
我查找了以下信息;但是设置typeNameHandling并没有解决问题。由于它是一个字典,因此我也不能使用类型名称属性装饰IConvertible值。
关于JSON.NET中反序列化接口的转换,请参考以下链接: Casting interfaces for deserialization in JSON.NET 我没有找到有关该主题的其他信息,因此非常需要帮助!
我还发现了这个解决方案,但它涉及创建ExpandableObjectConverter,这不是一个非常优雅的解决方案。
请参考以下链接: Problems using JSON.NET with ExpandableObjectConverter