I want to set a contract serializer just for certain types in my ASP.NET Web API application. I can set the settings globally in the App_Start/FormatterConfig.cs like this:
public static void RegisterGlobalFormatters(MediaTypeFormatterCollection formatters)
{
jsonSerializerSettings.ContractResolver = new CriteriaContractResolver(new List<string>(new string[]{"mdData", "name", "label"}));
...
but how can I just apply this to one or more specific class types?
The reason I want to do this is because I need to be able to set what fields should be serialized at runtime based on configuration or parameters to the web service similar to these examples:
I would try creating something like this
and then insert this into the beginning of the formatters collection
I ended up using a JsonConverter that only writes the parameters that are specified in the "properties" list. It's more low level than a ContractResolver or a formatter, but I don't think it's possible to configure either one for a specific type.
This can be applied to a class using the attribute:
This seems like a hack though, I think I should use the contract resolver to get the list of properties to serialize instead of using reflection directly, but I'm not sure how.
You have a few options: