我正在尝试使用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!");
}
}
答案 0 :(得分:20)
您需要使用自定义合约解析程序。仅当未为类型指定转换器时,默认合同解析程序才使用转换器设置。
class CustomContractResolver : DefaultContractResolver
{
protected override JsonConverter ResolveContractConverter (Type objectType)
{
if (typeof(Foo).IsAssignableFrom(objectType))
return null; // pretend converter is not specified
return base.ResolveContractConverter(objectType);
}
}
用法:
JsonConvert.DeserializeObject<Foo>("{}", new JsonSerializerSettings {
ContractResolver = new CustomContractResolver(),
Converters = new[] { new CustomConverter() },
});