我想序列化一个可能包含
示例代码: (DotNetFiddle: https://dotnetfiddle.net/UvphQO)
生成的输出结果:
如预期,字典中的
我可以采用许多方法来解决这个问题,但首选解决方案是找出为什么在这种情况下序列化程序会对
System.Drawing.Color
值或其他类型的Dictionary<string, object>
。我使用带有TypeNameHandling.Auto
的序列化程序,这对大多数类有效,但不适用于Color
。示例代码: (DotNetFiddle: https://dotnetfiddle.net/UvphQO)
public class Program
{
class A { }
class B { }
public static void Main()
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict["Foo"] = new A();
dict["Bar"] = new B();
dict["Baz"] = new object();
dict["Rainbow"] = Color.FromArgb(20, 20, 20, 20);
var ser = new JsonSerializer
{
TypeNameHandling = TypeNameHandling.Auto
};
var w = new JsonTextWriter(Console.Out)
{
Formatting = Formatting.Indented
};
ser.Serialize(w, dict);
}
}
生成的输出结果:
{
"Foo": {
"$type": "Program+A, mi1i2eqo"
},
"Bar": {
"$type": "Program+B, mi1i2eqo"
},
"Baz": {},
"Rainbow": "20, 20, 20, 20"
}
如预期,字典中的
A
或 B
实例具有重构所需的 $type
元数据。但是,Color
的实例则没有。当此 JSON 反序列化时,dict["Rainbow"]
是一个 System.String
。我可以采用许多方法来解决这个问题,但首选解决方案是找出为什么在这种情况下序列化程序会对
$type
执行看似不正确的操作。
TypeConverter
的类型。 - user12864