且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在自定义JsonConverter中使用默认序列化

更新时间:2023-02-12 08:38:08

在您的自定义 JsonConverter ,覆盖 CanWrite 并返回错误:

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();
}

然后,您只能从WriteJson引发异常,因为它不会被调用.

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

(类似地,要在 de 序列化期间获得默认行为,请覆盖

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

请注意, JsonConverter<T> 可以使用相同的方法(在 Json.NET 11.0.1 中引入),因为它是只是JsonConverter的子类,它引入了 WriteJson() .

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().