Sto tentando di deserializzare una classe utilizzando Json.NET e un oggetto JsonConverter personalizzato. La classe attualmente definisce un convertitore per la serializzazione predefinita utilizzando JsonConverterAttribute. Devo fare una deserializzazione personalizzata passando in un convertitore personalizzato. Tuttavia, la deserializzazione sembra ancora utilizzare il convertitore predefinito. Come posso convincere Json.NET a preferire il mio convertitore personalizzato?Json.NET come sovrascrivere la serializzazione per un tipo che definisce un JsonConverter personalizzato tramite un attributo?
Ecco un po 'di codice di esempio che dimostra il problema. Utilizzo 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!");
}
}