如何在 ASP.NET Web API 中为 Json.NET 设置自定义 JsonSerializerSettings? [英] How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?
问题描述
我知道 ASP.NET Web API 本机使用 Json.NET 来(反)序列化对象,但是有没有办法指定您希望它使用的 JsonSerializerSettings
对象?
I understand that ASP.NET Web API natively uses Json.NET for (de)serializing objects, but is there a way to specify a JsonSerializerSettings
object that you want for it to use?
例如,如果我想在序列化的 JSON 字符串中包含 type
信息怎么办?通常我会在 .Serialize()
调用中注入设置,但 Web API 会默默地做到这一点.我找不到手动注入设置的方法.
For example, what if I wanted to include type
information into the serialized JSON string? Normally I'd inject settings into the .Serialize()
call, but Web API does that silently. I can't find a way to inject settings manually.
推荐答案
您可以使用 中的
对象.Formatters.JsonFormatter.SerializerSettings
属性自定义 JsonSerializerSettings
HttpConfiguration
You can customize the JsonSerializerSettings
by using the Formatters.JsonFormatter.SerializerSettings
property in the HttpConfiguration
object.
例如,您可以在 Application_Start() 方法中执行此操作:
For example, you could do that in the Application_Start() method:
protected void Application_Start()
{
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.Formatting =
Newtonsoft.Json.Formatting.Indented;
}
这篇关于如何在 ASP.NET Web API 中为 Json.NET 设置自定义 JsonSerializerSettings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!