Registering a custom JsonConverter globally in Json.Net
Yes, this is possible using Json.Net 5.0.5 or later. See JsonConvert.DefaultSettings
.
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Converters = new List<JsonConverter> { new SomeConverter() }
};
// Later on...
string json = JsonConvert.SerializeObject(someObject); // this will use SomeConverter
If you're using Web API, you can set up a converter globally like this instead:
var config = GlobalConfiguration.Configuration;
var jsonSettings = config.Formatters.JsonFormatter.SerializerSettings;
jsonSettings.Converters.Add(new SomeConverter());
Another approach (which wins in priority over the one @Brian mentions above) is to implement a custom contract resolver
JsonFormatter.SerializerSettings.ContractResolver = new CustomContractResolver();
And the implementation is rather straightforward
public class CustomContractResolver : DefaultContractResolver
{
private static readonly JsonConverter _converter = new MyCustomConverter();
private static Type _type = typeof (MyCustomType);
protected override JsonConverter ResolveContractConverter(Type objectType)
{
if (objectType == null || !_type.IsAssignableFrom(objectType)) // alternatively _type == objectType
{
return base.ResolveContractConverter(objectType);
}
return _converter;
}
}
Both methods are valid, this one is just a bigger hammer