如何在MVC 4 API中漂亮的打印JSON脚本

时间:2020-12-26 21:44:19

How can I get the following JSON response to look cleaner using MVC 4 API. This is a sample JSON

如何使用MVC 4 API使以下JSON响应看起来更简洁。这是一个JSON示例。

{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Price":3.99}

Pretty JSON

漂亮的JSON

{
  "Name":"Apple",
  "Expiry":"2008-12-28T00:00:00",
  "Price":3.99
}

4 个解决方案

#1


7  

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

如果您正在使用Web Api。你可以设置:

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

#2


3  

You can do this using Json.net NuGet package:

你可以使用Json.net NuGet包:

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

#3


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.

动机:如果查询字符串包含单词prettyprint或prettyprint=true,那么如果查询字符串中没有单词prettyprint或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.

步骤1:定义一个自定义操作过滤器属性,如下所示。

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.

步骤2:全局配置这个过滤器。

public static void Register(HttpConfiguration config)
    {            
        config.Filters.Add(new PrettyPrintFilterAttribute());       
    }

#4


0  

If it's an object that you're serializing into JSON, you can just add a parameter to "prettify" it.

如果是要序列化为JSON的对象,只需添加一个参数来“美化”它。

JsonConvert.SerializeObject(object, Formatting.Indented);

#1


7  

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

如果您正在使用Web Api。你可以设置:

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

#2


3  

You can do this using Json.net NuGet package:

你可以使用Json.net NuGet包:

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

#3


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.

动机:如果查询字符串包含单词prettyprint或prettyprint=true,那么如果查询字符串中没有单词prettyprint或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.

步骤1:定义一个自定义操作过滤器属性,如下所示。

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.

步骤2:全局配置这个过滤器。

public static void Register(HttpConfiguration config)
    {            
        config.Filters.Add(new PrettyPrintFilterAttribute());       
    }

#4


0  

If it's an object that you're serializing into JSON, you can just add a parameter to "prettify" it.

如果是要序列化为JSON的对象,只需添加一个参数来“美化”它。

JsonConvert.SerializeObject(object, Formatting.Indented);