Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

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.

like image 436
Richard Neil Ilagan Avatar asked Nov 07 '12 17:11

Richard Neil Ilagan


People also ask

Can ASP Net Web API specialize to XML or JSON?

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.


2 Answers

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; } 
like image 127
carlosfigueira Avatar answered Sep 22 '22 20:09

carlosfigueira


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

like image 22
smockle Avatar answered Sep 22 '22 20:09

smockle