【发布时间】:2021-04-15 23:42:53
【问题描述】:
我使用的是 .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;}-> 引发运行时错误,无法转换
fwiw,我正在使用声明
[JsonConverter(typeof(ThingConverter))]
public class Thing{
}
全局注册转换器。
【问题讨论】:
-
似乎不可能让
System.Text.Json为您已将[JsonConverter(typeof(ThingConverter))]直接应用于类型本身的类型生成默认序列化。如果将转换器应用于选项或特定属性,则有一些方法可以做到这一点。请参阅:How to use default serialization in a custom System.Text.Json JsonConverter?。