How to use default serialization in a custom JsonConverter

后端 未结 1 1824
栀梦
栀梦 2020-11-27 07:21

I have a complex object graph that I am serializing/deserializing with Json.NET. Some of the objects derive from an abstract class, so in order for the deserialization to wo

相关标签:
1条回答
  • 2020-11-27 07:50

    In your custom JsonConverter, override CanWrite and return false:

    public override bool CanWrite { get { return false; } }
    
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
    

    Then you can just throw an exception from WriteJson, since it won't get called.

    (Similarly, to get default behavior during deserialization, override CanRead and return false.)

    Note that the same approach can be used for JsonConverter<T> (introduced in Json.NET 11.0.1) since it is just a subclass of JsonConverter that introduces type-safe versions of ReadJson() and WriteJson().

    0 讨论(0)
提交回复
热议问题