每种类型的自定义Json.NET串行设置 [英] Custom Json.NET serializer settings per type
问题描述
我使用它使用全球HttpConfiguration类指定JsonFormatter设置的ApiController。我可以全局设置序列设置很容易如下:
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;
问题是,并非所有的设置适用于所有类型在我的项目。我要指定执行多态系列化的特定类型的自定义TypeNameHandling和活页夹选项。
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.
我怎么可以在每个类型的,或者至少在每个ApiController的基础上指定JsonFormatter.SerializationSettings?
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);
}
}
这篇关于每种类型的自定义Json.NET串行设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!