2013-06-28 9 views
15

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!"); 
    } 
} 

risposta

17

È necessario utilizzare il resolver del contratto personalizzato. Il resolver del contratto predefinito utilizza i convertitori dalle impostazioni solo se il convertitore non è specificato per il tipo.

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); 
    } 
} 

Usage:

JsonConvert.DeserializeObject<Foo>("{}", new JsonSerializerSettings { 
    ContractResolver = new CustomContractResolver(), 
    Converters = new[] { new CustomConverter() }, 
}); 
Problemi correlati