Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a JsonConverter with JToken.ToObject<>() method?

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?

like image 835
Mike Scott Avatar asked Apr 02 '15 20:04

Mike Scott


1 Answers

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

like image 187
Brian Rogers Avatar answered Oct 05 '22 08:10

Brian Rogers