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

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

本文介绍了如何在自定义JsonConverter中使用默认序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的对象图,正在使用Json.NET进行序列化/反序列化.一些对象是从抽象类派生的,因此为了使反序列化正常工作,我需要创建一个自定义JsonConverter.它的唯一作用是在反序列化时选择抽象类的适当具体实现,并允许Json.NET继续其发展.

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 work properly, I needed to create a custom JsonConverter. Its only role is to select the appropriate concrete implementation of the abstract class at deserialization-time and allow Json.NET to continue on its way.

我想序列化时出现问题.我根本不需要做任何自定义.我希望获得与使用JsonConvert.SerializeObject且没有自定义JsonConverter的行为完全相同的行为.

My problem comes when I want to serialize. I don't need to do anything custom at all. I want to get exactly the same behavior as I would get using JsonConvert.SerializeObject with no custom JsonConverter.

但是,由于我将自定义JsonConverter类用于反序列化需求,因此我不得不提供WriteJson实现.由于WriteJson是抽象的,因此我不能只调用base.WriteJson,但实际上我想这样做.因此,我的问题是,我应采用哪种方法来获得简·简的默认行为?换句话说:

However, since I'm using the custom JsonConverter class for my deserialization needs, I'm forced to supply a WriteJson implementation. Since WriteJson is abstract, I can't just call base.WriteJson, but I want to do essentially that. So my question is, what do I put in that method to get the plain-Jane, default behavior? In other words:

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
    // What goes here to get default processing?
}

推荐答案

在您的自定义 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 序列化期间获得默认行为,请覆盖 CanRead 并返回false.)

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

这篇关于如何在自定义JsonConverter中使用默认序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:03