Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

json.net

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.

like image 433
user12864 Avatar asked Sep 11 '25 02:09

user12864


1 Answers

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
like image 72
Brian Rogers Avatar answered Sep 12 '25 17:09

Brian Rogers