简体   繁体   中英

JavaScriptSerializer is not deserializing System.Drawing.Color. How to deserialize Color object?

I have serialized System.Drawing.Color in JSON using JavaScriptSerializer, but when i try to de-serialize it, it returns Color object with All the values 0.

Sample JSON is as below.

{
    "A":255,
    "B":0,
    "G":165,
    "IsEmpty":false,
    "IsKnownColor":true,
    "IsNamedColor":true,
    "IsSystemColor":false,
    "Name":"Orange",
    "R":255
}

Here is the screen shot of how deserialized object looks like.

在此处输入图片说明

Then i tried using JSON.net(newtonsoft.json) library. It gives me below error.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Drawing.Color' because the type requires a JSON string value to deserialize correctly.

Is there any way of deserialzing JSON to color object.i have found this similar question without any answere.

Json.NET serializes System.Drawing.Color just fine.

Color c = Color.FromArgb(169, 170, 171, 172);
Console.WriteLine(c); //Color [A=169, R=170, G=171, B=172]
string colorStr = JsonConvert.SerializeObject(c);
Console.WriteLine(colorStr); //"169, 170, 171, 172"
Color c1 = JsonConvert.DeserializeObject<Color>(colorStr);
Console.WriteLine(c1); //Color [A=169, R=170, G=171, B=172]

Tested against Json.NET 6.0.3

也许您可以使用System.Drawing.ColorTranslator.ToHtml将颜色实例转换为表示html中颜色的十六进制字符串,并按照XmlSerializer和System.Drawing.Color的最佳解决方案中的建议使用ColorTranslator.FromHtml将其反序列化。

Since i had very complex JSON. I achieved deserialization using Color.FromArgb and CustomCreationConverter . Here is how i made it using Json.net library.

I created a class which is responsible for handling deserialization for System.Drawing.Color class from JSON string. you can find simple example at JSON.net site.

public class ColorConverter : CustomCreationConverter<Color>
{
    public override bool CanWrite { get { return false; } }
    public override bool CanRead { get { return true; } }
    public ColorConverter(){ }
    public override Color Create(Type objectType)
    {
        return new Color();
    }
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jObject = JObject.Load(reader);
        Color target = Create(objectType);
        target = Color.FromArgb(jObject["A"].Value<Int32>(), jObject["R"].Value<Int32>(), jObject["G"].Value<Int32>(), jObject["B"].Value<Int32>());
        return target;
    }
}

When deserializing pass instance of class that you have created to handle custom deserialization logic

MyModelName obj = JsonConvert.DeserializeObject<MyModelName>(json, new ColorConverter());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM