Format JSON Output in Asp.Net Web API

In the previous article, we discuss how to return the data in JSON format from Asp.Net Web API. Today we discuss how to format that JSON data. Here we display the JSON data in proper format as well as will convert the data into Camel case. Change the WebApiConfig.Register() method, as shown below, to display the data in an appropriate format.

public static class WebApiConfig
{
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Web API routes
            config.MapHttpAttributeRoutes(); 

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
            config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
            config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        }
}

Run the application and request for GetEmployees() method; it displays the data in the proper format, as shown below.

                                     

                                                                                                 CompanyRestAPI-4.zip (55.60 mb)