Customize Json result in Web API

If you work with Visual Studio 2015 and WebAPI, this short post is for you!

We have to make our Web API project easy to debug so, I’m going to remove the XML formatter. I’m doing that because I’m in a test project and I’d like to see the response in the browser. The easily way to force the response to Json for all Web API requests is to remove the XML. Obviously you shouldn't do it in production.

Global.asax

var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);

Now we can start change the setting for all Json responses accessing to GlobalConfiguration.Configuration.Formatters.JsonFormatter.

In the following examples I’ll use always the class below (create it under Models folder):

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PSC.Models
{
    public class MapModel
    {
        public string Firstname { get; set; }
        public string Lastname { get; set; }
        public string Username { get; set; }
        public DateTime Birthdate { get; set; }
        public Uri Website { get; set; }
        public int Age { get; set; }
        public double Salary { get; set; }

        [JsonIgnore]
        public string IgnoreProperty { get; set; }
    }
}

Now we customize the Global.asax again to reply with the correct format. Change the Global.asax as following code:

using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace PSC
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // start change the setting for all Json responses accessing to
            // GlobalConfiguration.Configuration.Formatters.JsonFormatter
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            // How can we indent the json response?
            json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
            // How can we change the case in the response?
            json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            // How can we manage the null in the response?
            json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            // How can we change the DateTime format?
            json.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
            // How can we change the TimeZone format?
            //json.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
            // How can we change the Culture of the serializer?
            // json.SerializerSettings.Culture = new CultureInfo("en-GB");

            var formatters = GlobalConfiguration.Configuration.Formatters;
            formatters.Add(json);
        }
    }
}

Then under Controllers create a new one and add the following code:

using Newtonsoft.Json.Serialization;
using PSC.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web.Http;

namespace PSC.Controllers
{
    public class MapController : ApiController
    {
        public HttpResponseMessage Get()
        {
            IList<mapmodel> result = new List<mapmodel>();
            result.Add(new MapModel
            {
                Age = 34,
                Birthdate = DateTime.Now,
                Firstname = "Enrico",
                Lastname = "Rossini",
                IgnoreProperty = "This text should not appear in the reponse",
                Salary = 1000,
                Username = "enrico",
                Website = new Uri("http://puresourcecode.com")
            });

            var formatter = new JsonMediaTypeFormatter();
            var json = formatter.SerializerSettings;

            json.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;
            json.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc;
            json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            json.Formatting = Newtonsoft.Json.Formatting.Indented;
            json.ContractResolver = new CamelCasePropertyNamesContractResolver();
            json.Culture = new CultureInfo("en-GB");

            return Request.CreateResponse(HttpStatusCode.OK, result, formatter);
        }
    }
}

The result is pretty cool!

webapi-json

Happy coding!

Comments (1) -

Stephanie Lawrence
4/7/2016 7:52:18 PM #

Thanks for some other informative site. Where else could I get that kind of info written in such a perfect method? I've a project that I'm just now operating on, and I have been at the glance out for such information.

Add comment

Advertsing

125X125_06





TagCloud

MonthList

CommentList