C# – How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API

asp.net-web-apicjson.net

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?

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.

Best Answer

You can customize the JsonSerializerSettings by using the Formatters.JsonFormatter.SerializerSettings property in the HttpConfiguration object.

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