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

半城伤御伤魂 提交于 2019-12-21 07:27:13

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/29421904/how-to-use-a-jsonconverter-with-jtoken-toobject-method

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