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.
Web API provides media-type formatters for both JSON and XML. The framework inserts these formatters into the pipeline by default. Clients can request either JSON or XML in the Accept header of the HTTP request.
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; } 
                        You can specify JsonSerializerSettings for each JsonConvert, and you can set a global default.
Single JsonConvert with an overload:
// Option #1. JsonSerializerSettings config = new JsonSerializerSettings { ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore }; this.json = JsonConvert.SerializeObject(YourObject, Formatting.Indented, config);  // Option #2 (inline). JsonConvert.SerializeObject(YourObject, Formatting.Indented,     new JsonSerializerSettings() {         ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore     } );   Global Setting with code in Application_Start() in Global.asax.cs:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings {      Formatting = Newtonsoft.Json.Formatting.Indented,      ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore };   Reference: https://github.com/JamesNK/Newtonsoft.Json/issues/78
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With