Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web API: Configure JSON serializer settings on action or controller level

Overriding the default JSON serializer settings for web API on application level has been covered in a lot of SO threads. But how can I configure its settings on action level? For example, I might want to serialize using camelcase properties in one of my actions, but not in the others.

like image 996
Johan Avatar asked Jun 12 '17 12:06

Johan


People also ask

What is JsonSerializerOptions?

JsonSerializerOptions() Initializes a new instance of the JsonSerializerOptions class. JsonSerializerOptions(JsonSerializerDefaults) Constructs a new JsonSerializerOptions instance with a predefined set of options determined by the specified JsonSerializerDefaults.

Which line of code can you use to format JSON data in camel case?

If you want JsonSerializer class to use camel casing you can do the following: var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy. CamelCase }; string json = JsonSerializer. Serialize(empList, options); return Ok(json);

Which is a formatter class for JSON?

JSON formatting is provided by the JsonMediaTypeFormatter class.

What is Jsonserializersettings?

Specifies the settings on a JsonSerializer object.


2 Answers

Option 1 (quickest)

At action level you may always use a custom JsonSerializerSettings instance while using Json method:

public class MyController : ApiController {     public IHttpActionResult Get()     {         var settings = new JsonSerializerSettings         {             ContractResolver = new CamelCasePropertyNamesContractResolver()         };         var model = new MyModel();         return Json(model, settings);     } } 

Option 2 (controller level)

You may create a new IControllerConfiguration attribute which customizes the JsonFormatter:

public class CustomJsonAttribute : Attribute, IControllerConfiguration  {     public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)     {         var formatter = controllerSettings.Formatters.JsonFormatter;          controllerSettings.Formatters.Remove(formatter);          formatter = new JsonMediaTypeFormatter         {             SerializerSettings =             {                 ContractResolver = new CamelCasePropertyNamesContractResolver()             }         };          controllerSettings.Formatters.Insert(0, formatter);     } }  [CustomJson] public class MyController : ApiController {     public IHttpActionResult Get()     {         var model = new MyModel();         return Ok(model);     } } 
like image 113
Federico Dipuma Avatar answered Sep 19 '22 06:09

Federico Dipuma


Here's an implementation of the above as Action Attribute:

public class CustomActionJsonFormatAttribute : ActionFilterAttribute {     public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)     {         if (actionExecutedContext?.Response == null) return;          var content = actionExecutedContext.Response.Content as ObjectContent;          if (content?.Formatter is JsonMediaTypeFormatter)         {             var formatter = new JsonMediaTypeFormatter             {                 SerializerSettings =                 {                     ContractResolver = new CamelCasePropertyNamesContractResolver()                 }             };              actionExecutedContext.Response.Content = new ObjectContent(content.ObjectType, content.Value, formatter);         }     } }  public class MyController : ApiController {     [CustomActionJsonFormat]     public IHttpActionResult Get()     {         var model = new MyModel();         return Ok(model);     } } 
like image 43
Dimitri Avatar answered Sep 20 '22 06:09

Dimitri