我有一堆自定义JsonConverter
,其中一些负责序列化,还有一些反序列化。我使用JsonSerializer
属性将其添加到Converters
。
我的问题是,如果我有一个JsonConverter
用于序列化特定类型,而另一个用于反序列化相同类型,则不会为特定任务选择正确的JsonConverter
,它始终是第一个Converters
列表中的一个,其中CanConvert返回true,无论是否JsonConverter
CanWrite
,都会选择该值。
在下面的示例中,CustomConverterA
和CustomConverterB
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
应该像这样工作吗?我不应该让不同的类处理序列化和反序列化吗?如果没有,CanRead
和gstreamer
属性的目的是什么?