gpt4 book ai didi

c# - 每种类型的自定义 Json.NET 序列化程序设置

转载 作者:可可西里 更新时间:2023-11-01 09:05:17 25 4
gpt4 key购买 nike

我正在使用 ApiController,它使用全局 HttpConfiguration 类来指定 JsonFormatter 设置。我可以很容易地按如下方式全局设置序列化设置:

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

问题是并非所有设置都适用于我项目中的所有类型。我想为执行多态序列化的特定类型指定自定义 TypeNameHandling 和 Binder 选项。

如何在每个类型或至少在每个 ApiController 的基础上指定 JsonFormatter.SerializationSettings?

最佳答案

根据您上面的评论,以下是每个 Controller 配置的示例:

[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);
}
}

关于c# - 每种类型的自定义 Json.NET 序列化程序设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17684925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com