user1846231
user1846231

Reputation: 315

Custom JsonConverter does not call ReadJson

I am trying to implement a custom JsonConverter for a struct, but I'm having a hard time getting it to work. I have previously implemented a custom converter for another class and that one works flawlessly, I thought I did the same thing for this one but the ReadJson method of my converter is never called.

This is the class:

public class TransformMatrixConverter : JsonConverter
{
  public override bool CanConvert(Type objectType)
  {
    return typeof(TransformMatrix).IsAssignableFrom(objectType);
  }

  public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
  {
    throw new NotImplementedException();
  }

  public override bool CanWrite
  {
    get { return false; }
  }

  public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
  {
    throw new NotImplementedException();
  }
}

And below is how I use it in my Item class. You can see my other converter, which works fine.

public static Item FromJSON(string json)
{
  JsonConverter[] converters = { new LineConverter(), new TransformMatrixConverter() };
  return JsonConvert.DeserializeObject<Item>(json, new JsonSerializerSettings()
  {
    Converters = converters
  });
}

What happens: the CanConvert method of my converter is called and correctly returns true when appropriate; however, the ReadJson method is never hit, I have a breakpoint there and also that exception is never thrown. I have verified that the CanRead property of the converter is true. I am at a loss here, any ideas?

Upvotes: 4

Views: 3660

Answers (1)

user1846231
user1846231

Reputation: 315

I think I solved it with the help of Brian, the problem was unrelated to the code above - the TransformMatrix I thought I was deserializing was just a read-only property. The solution I used was to expose another property which the deserializer can write.

Upvotes: 1

Related Questions