I want to assign a JsonConverter to a class without using the [JsonConverter(typeof(...))]
attribute (because I'm doing some complex stuff with Web API that requires me to assign the JsonConverter in a different assembly than where the class is defined).
The answer to Globally use a JsonConverter on a class without the attribute almost answers my question. However my question is in regards to Web API so I'm unclear about:
- What base class should I use for my contract resolver? I suspect it should be
JsonContractResolver
but not sure whatMediaTypeFormatter
object to pass to its constructor. - What is the proper way to declare a custom contract resolver in Web API?
The code below is what I've tried but it does not work. My custom contract resolver does not get used and breakpoints in CreateObjectContract()
do not get hit.
Global.asax.cs
protected void Application_Start()
{
GlobalConfiguration.Configuration.Formatters.JsonFormatter
.SerializerSettings.ContractResolver =
new CustomResolver(GlobalConfiguration.Configuration.Formatters.JsonFormatter);
...
}
CustomResolver.cs
public class CustomResolver : JsonContractResolver
{
public CustomResolver(MediaTypeFormatter formatter) : base(formatter) { }
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
JsonObjectContract contract = base.CreateObjectContract(objectType);
if (typeof(MyBaseClass).IsAssignableFrom(objectType))
contract.Converter = new MyBaseClassJsonConverter();
return contract;
}
}