How to pretty-print JSON script in MVC 4 API

2020-08-16 08:39发布

问题:

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
}

回答1:

If you're using the Web Api. You can set:

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;


回答2:

You can do this using Json.net NuGet package:

JObject.Parse(json).ToString(Formatting.Indented)


回答3:

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());       
    }


回答4:

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);