Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JsonConverter do write json normally

Tags:

json.net

I'm writing a custom JsonConverter, but only really want to change the read logic. The write logic should perform normally. Any way I try it, I'm getting stack overflows, since Json.NET just goes straight back to the converter. Is there a way to specify that I don't want to customize the writer, or that I want to defer back to the normal Json.NET logic?

like image 924
heneryville Avatar asked May 16 '14 20:05

heneryville


1 Answers

It turns out that you can override a CanWrite property on the JsonConverter that will prevent Json.NET from calling the converter.

public class MyConverter: JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException(); //This will never be called since CanWrite is false
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        //Do your thing
        return new object();
    }

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

    public override bool CanConvert(Type objectType)
    {
        //Do your thing
        return true;
    }
}
like image 137
heneryville Avatar answered Sep 27 '22 17:09

heneryville