我正在使用 .NET Core 5,不使用 Newtonsoft。我正在编写一个自定义序列化程序,因为我的 JSON 输出情况很奇怪;但是我不介意使用标准的反序列化程序。
我有以下代码,遵循微软编写自定义 JsonConverters 的指南:
public class ThingConverter : JsonConverter<Thing>{
public override void Write(Utf8JsonWriter writer, Thing t, JsonSerializerOptions options){
// do stuff, this is fine
}
public override Thing Read(ref Utf8Reader reader, Type typeToConvert, JsonSerializerOptions options){
// i want the DEFAULT behaviour here.
}
}
有没有人知道如何使读取器的默认行为?
我尝试过的方法:
return JsonSerializer.Deserialize<Thing>(ref reader, options)
-> 导致无限循环- 添加
public override bool CanConvert(Type objectType){return false;}
-> 抛出运行时错误,无法转换
顺便说一下,我正在使用这个声明:
[JsonConverter(typeof(ThingConverter))]
public class Thing{
}
全局注册转换器。
System.Text.Json
为一个已应用[JsonConverter(typeof(ThingConverter))]
直接应用于类型本身 的类型生成默认序列化。如果转换器是在选项中应用或应用于特定属性,则有方法可以执行此操作。请参见:如何在自定义 System.Text.Json JsonConverter 中使用默认序列化?。 - dbc