简体   繁体   中英

Custom Json.NET serializer settings per type

I am using an ApiController which uses the global HttpConfiguration class to specify the JsonFormatter settings. I can globally set serialization settings as follows very easily:

config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;

The problem is that not all settings apply to all types in my project. I want to specify custom TypeNameHandling and Binder options for specific types that perform polymorphic serialization.

How can I specify JsonFormatter.SerializationSettings on a per-type or at the least on a per-ApiController basis?

Based on your comment above, following is an example of per-controller configuration:

[MyControllerConfig]
public class ValuesController : ApiController

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class MyControllerConfigAttribute : Attribute, IControllerConfiguration
{
    public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
    {
        //remove the existing Json formatter as this is the global formatter and changing any setting on it
        //would effect other controllers too.
        controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter);

        JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter();
        formatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All;
        controllerSettings.Formatters.Insert(0, formatter);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM