Removing Default Values in JSON with the MVC4 Web API

Here is how to get the MVC4 WebAPI to generate more efficient JSON by not including properties which have their DefaultValue.  Took me a bit of time to find out where to set this, and there’s lots of out-dated advice that applies to MVC3 or the beta of MVC4.  For your information, the released MVC4 uses JSON.net serialization by default, which is a good thing.

     public class JsonConfig
    {
        public static void Setup()
        {
            var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
            json.SerializerSettings.DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate;
        } 
    }

Call JasonConfig.Setup() from somewhere in your global.asax startup, such as in WebApiConfig.Register.

Now when you have a class with a default value of its property, that property will be skipped.

    public class Location    {
         [DefaultValue(false)]
         public bool Old { getset; }
         public double X { getset; }
         public double Y { getset; }
         public double Z { getset; }
     }

Old will not be written when serializing an instance of this class if it is set to “false”.That’s it!

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s