即使CanWrite返回false,也会选择Json.NET JsonConverter进行序列化

时间:2017-10-31 14:36:49

标签: c# json.net

我有一堆自定义JsonConverter,其中一些负责序列化,还有一些反序列化。我使用JsonSerializer属性将其添加到Converters

我的问题是,如果我有一个JsonConverter用于序列化特定类型,而另一个用于反序列化相同类型,则不会为特定任务选择正确的JsonConverter,它始终是第一个Converters列表中的一个,其中CanConvert返回true,无论是否JsonConverter CanWrite,都会选择该值。

在下面的示例中,CustomConverterACustomConverterB CanHandle string类型,但只有CustomConverterB可以写(唯一的区别是CanWrite返回CustomConverterB)为true。我希望能够选择CustomConverterB

但是选择了CustomConverterA,但从未调用过WriteJson方法。自CustomConverterB之前选择CustomConverterA以来,public class CustomConverterA : JsonConverter { public override bool CanWrite { get { Console.WriteLine("Inside CustomConverterA.CanWrite (returns false)"); return false; } } public override bool CanRead => true; public override bool CanConvert(Type objectType) { Console.WriteLine("Inside CustomConverterA.CanConvert"); if (objectType == typeof(string)) { Console.WriteLine("return true"); return true; } Console.WriteLine("return false"); return false; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { Console.WriteLine("Inside CustomConverterA.WriteJson"); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Console.WriteLine("Inside CustomConverterA.ReadJson"); return new object(); } } public class CustomConverterB : JsonConverter { public override bool CanWrite { get { Console.WriteLine("Inside CustomConverterB.CanWrite (returns true)"); return true; } } public override bool CanRead => true; public override bool CanConvert(Type objectType) { Console.WriteLine("Inside CustomConverterB.CanConvert"); if (objectType == typeof(string)) { Console.WriteLine("return true"); return true; } Console.WriteLine("return false"); return false; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { Console.WriteLine("Inside CustomConverterB.WriteJson"); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { Console.WriteLine("Inside CustomConverterB.ReadJson"); return new object(); } } public void TestCustomConverter() { var serializer = new JsonSerializer() { Converters = { new CustomConverterA(), new CustomConverterB() } }; var data = "testdata"; using (var writer = new StringWriter()) { serializer.Serialize(writer, data); var serialized = writer.ToString(); Console.WriteLine("Serialized: " + serialized); } } 被完全跳过。

Inside CustomConverterA.CanConvert
return true
Inside CustomConverterA.CanWrite (returns false)
Serialized: "testdata"

以上示例输出:

JsonConverter

CanWrite应该像这样工作吗?我不应该让不同的类处理序列化和反序列化吗?如果没有,CanReadgstreamer属性的目的是什么?

0 个答案:

没有答案