如何在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.
推荐答案
您可以使用HttpConfiguration
对象中的Formatters.JsonFormatter.SerializerSettings
属性来自定义JsonSerializerSettings
.
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屋!