How can I get the following JSON response to look cleaner using MVC 4 API. This is a sample JSON
{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Price":3.99}
Pretty JSON
{
"Name":"Apple",
"Expiry":"2008-12-28T00:00:00",
"Price":3.99
}
How can I get the following JSON response to look cleaner using MVC 4 API. This is a sample JSON
{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Price":3.99}
Pretty JSON
{
"Name":"Apple",
"Expiry":"2008-12-28T00:00:00",
"Price":3.99
}
If you're using the Web Api. You can set:
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
You can do this using Json.net NuGet package:
JObject.Parse(json).ToString(Formatting.Indented)
Motivation: Pretty print if the query string contains the word prettyprint
or prettyprint=true
, don't pretty print if the there's no word prettyprint
in the query string or prettyprint=false
.
Note: This filter checks for pretty print in every request. It is important to turn off the pretty print feature by default, enable only if request.
Step 1: Define a Custom action filter attribute as below.
public class PrettyPrintFilterAttribute : ActionFilterAttribute
{
/// <summary>
/// Constant for the query string key word
/// </summary>
const string prettyPrintConstant = "prettyprint";
/// <summary>
/// Interceptor that parses the query string and pretty prints
/// </summary>
/// <param name="actionExecutedContext"></param>
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
JsonMediaTypeFormatter jsonFormatter = actionExecutedContext.ActionContext.RequestContext.Configuration.Formatters.JsonFormatter;
jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
var queryString = actionExecutedContext.ActionContext.Request.RequestUri.Query;
if (!String.IsNullOrWhiteSpace(queryString))
{
string prettyPrint = HttpUtility.ParseQueryString(queryString.ToLower().Substring(1))[prettyPrintConstant];
bool canPrettyPrint;
if ((string.IsNullOrEmpty(prettyPrint) && queryString.ToLower().Contains(prettyPrintConstant)) ||
Boolean.TryParse(prettyPrint, out canPrettyPrint) && canPrettyPrint)
{
jsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
}
}
base.OnActionExecuted(actionExecutedContext);
}
}
Step 2: Configure this filter globally.
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new PrettyPrintFilterAttribute());
}
If it's an object that you're serializing into JSON, you can just add a parameter to "prettify" it.
JsonConvert.SerializeObject(object, Formatting.Indented);