我正在尝试使用 Json.NET 和自定义 JsonConverter 对象反序列化一个类。该类当前使用 JsonConverterAttribute 定义了一个用于默认序列化的转换器。我需要通过传入自定义转换器来进行自定义反序列化。但是,反序列化似乎仍然使用默认转换器。如何让 Json.NET 更喜欢我的自定义转换器?
这是一些演示该问题的示例代码。我正在使用 NewtonSoft.Json 4.5.11:
void Main()
{
JsonConvert.DeserializeObject<Foo>("{}"); // throws "in the default converter"
var settings = new JsonSerializerSettings { Converters = new[] { new CustomConverter() } };
JsonConvert.DeserializeObject<Foo>("{}", settings); // still throws "in the default converter" :-/
}
[JsonConverter(typeof(DefaultConverter))]
public class Foo {
}
public class DefaultConverter : JsonConverter {
public override bool CanConvert(Type objectType)
{
return typeof(Foo).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new Exception("in the default converter!");
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new Exception("in the default converter!");
}
}
public class CustomConverter : JsonConverter {
public override bool CanConvert(Type objectType)
{
return typeof(Foo).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new Exception("in the custom converter!");
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new Exception("in the custom converter!");
}
}