DeserializeObject should support JToken property

Nov 30, 2010 at 6:08 PM

Consider a class with a JToken property that I want to serialize with JsonConvert:

class Response
{
    public string Name { get; set; }
    public JToken Data { get; set; }
}

JsonConvert.SerializeObject works fine. JsonConvert.DeserializeObject does not: "Cannot deserialize JSON object into type 'Newtonsoft.Json.Linq.JToken'."

If I change the type of Data to JObject (or JArray or JValue) it works fine, but it seems like an arbitrary JToken should be supported as well.

A simple enough workaround is to create my own JsonConverter:

class JTokenJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(JToken).IsAssignableFrom(objectType);
    }
	
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return JToken.ReadFrom(reader);
    }
	
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        ((JToken) value).WriteTo(writer);
    }
}

Coordinator
Dec 1, 2010 at 8:08 AM

Done. It was just a 1 line bug.