I'm reading a large JSON file successfully into JObjects. One of the types I'm deserializing into has a property of type System.Drawing.Color. The JSON for this property has an integer value representing the color. When I try to do a ToObject() I get
Error converting value 16711680 to type 'System.Drawing.Color'.
The solution seems to be a simple JsonConverter that can convert from an integer to a Color but I can't find out how to use the converter with an existing JObject. Am I missing something obvious?
There is an overload of ToObject<T>
that accepts a JsonSerializer
. The serializer has a Converters
collection into which you can add your converter.
Here is a short demo:
using System;
using System.Drawing;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
JObject obj = JObject.Parse(@"{ ""Color"" : 16711680 }");
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new ColorConverter());
Color c = obj["Color"].ToObject<Color>(serializer);
Console.WriteLine(c.ToString());
}
}
class ColorConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(Color));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((Color)value).ToArgb());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return Color.FromArgb(Convert.ToInt32(reader.Value));
}
}
Output:
Color [A=0, R=255, G=0, B=0]
Fiddle: https://dotnetfiddle.net/ZA22mD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With