JSON.NET serialization of System.Drawing.Color with TypeNameHandling

六月ゝ 毕业季﹏ 提交于 2020-02-04 10:35:07

问题


I want to serialize a Dictionary<string, object> that may contain System.Drawing.Color values or other types as values. I create a serializer with TypeNameHandling.Auto, and this works for most classes, but not Color.

Example code: (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);
    }
}

The resulting output:

{
  "Foo": {
    "$type": "Program+A, mi1i2eqo"
  },
  "Bar": {
    "$type": "Program+B, mi1i2eqo"
  },
  "Baz": {},
  "Rainbow": "20, 20, 20, 20"
}

As expected, instances of A or B in the dictionary have the needed $type metadata for reconstruction. But instances of Color do not. When this json is deserialized, dict["Rainbow"] is a System.String.

There are many ways I could work around this, but the preferred solution would be to figure out why the serializer is doing something seemingly incorrect with $type in this case.


回答1:


The problem is that System.Drawing.Color has an associated TypeConverter, which Json.Net uses to convert the type to a string value and back. However, since the output value is a string (not an complex object), Json.Net does not output any type information for it. This causes an issue during deserialization if your property is defined as object instead of strongly typed: Json.Net won't be able to find the TypeConverter, so it will not be able to convert the string value back into a Color.

One way to work around the issue is to wrap the Color in another class which has a strongly-typed property for the color value.

class ColorHolder
{
    public System.Drawing.Color Value { get; set; }
}

Json.Net will then write out type information for the wrapper class, which will allow the nested Color struct to be deserialized correctly. Here is a round-trip demo:

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, object> dict = new Dictionary<string, object>();
        dict["Rainbow"] = new ColorHolder { Value = Color.FromArgb(10, 20, 30, 40) };

        JsonSerializerSettings settings = new JsonSerializerSettings
        {
            TypeNameHandling = TypeNameHandling.Auto,
            Formatting = Formatting.Indented
        };

        string json = JsonConvert.SerializeObject(dict, settings);
        Console.WriteLine(json);
        Console.WriteLine();

        var d = JsonConvert.DeserializeObject<Dictionary<string, object>>(json, settings);

        ColorHolder holder = (ColorHolder)d["Rainbow"];
        Console.WriteLine("A=" + holder.Value.A);
        Console.WriteLine("R=" + holder.Value.R);
        Console.WriteLine("G=" + holder.Value.G);
        Console.WriteLine("B=" + holder.Value.B);
    }
}

Output:

{
  "Rainbow": {
    "$type": "JsonTest.ColorHolder, JsonTest",
    "Value": "10, 20, 30, 40"
  }
}

A=10
R=20
G=30
B=40



回答2:


The System.Drawing.Color is a structure, and not a class in .NET. That sounds like an answer to your problem. Try to wrap it up with a class, or create your own color class and it should solve it.



来源:https://stackoverflow.com/questions/27584530/json-net-serialization-of-system-drawing-color-with-typenamehandling

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!