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.

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.

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?
}

推荐答案

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.

(类似地,要在de序列化期间获得默认行为,请重写CanRead并返回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().

Json相关问答推荐

抓取低于w jolt的对象级别

如何使用JQ将JSON字符串替换为解析后的类似功能?

Vega Lite中的图例对齐

Golang返回的JSON顶级字段是可变的.如何在 struct 中使用

Jolt变换将字段移动到数组的每个元素中

如何对未知/变量键的字典进行编码?

将=分隔值文件转换为:json文件

使用 serde 和 csv crates 将嵌套的 json 对象序列化为 csv

如何在不使用 Newtonsoft.JSON 的情况下序列化/反序列化

将 JSON 字符串解析为 Kotlin Android 中的对象列表(MOSHI?)

JOLT JSON 将值从一对多转换为一对一

在 Perl Mojolicious 中呈现 JSON 时防止转义字符

使用基本身份验证通过 CURL 发布 JSON

可以通过 POST 使用 EventSource 传递参数的服务器发送事件 (SSE)

ASP.NET MVC - 将 Json 结果与 ViewResult 结合起来

如何在不解析的情况下在javascript中同步包含JSON数据?

JSON对象中的JavaScript递归搜索

有没有办法折叠 Postman 中的所有 json 字段

SCRIPT5009:JSON未定义

Javascript:如何判断 AJAX 响应是否为 JSON