Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uuklanger/fa95ca9544c0d65133e35c7711849e5c to your computer and use it in GitHub Desktop.
Save uuklanger/fa95ca9544c0d65133e35c7711849e5c to your computer and use it in GitHub Desktop.
HOWTO - Control formatting of JSON in an IHttpActionResult REST API Response

Overview

In some cases, you may have an object the you are returning in an System.Web.Http.IHttpActionResult response where properties in the object you are returning have null values. To minimize the size of the data structure you are returning, a formatter can be specified which will let you supress null values.

Formatter

Add using System.Net.Http.Formatting to the top of your code file.

protected JsonMediaTypeFormatter getJsonFormatter()
{
   JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter
   {
       SerializerSettings =
       {
           NullValueHandling = NullValueHandling.Ignore
       }
    };

    return formatter;
}

Using Within Your Response

Lets say you have a list of interesting things called model_list which you load into a response object called ResponseDetailModel and you want to return this as JSON in a HTTP OK response, you can make the following call.

return Content(HttpStatusCode.OK, new ResponseDetailsModel(model_list), getJsonFormatter());

Final Thoughts

Like magic, your client will receive json with "content-type": "application/json; charset=utf-8" in the header that has no null properties.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment