.net JSON 序列化时如何使用 JavaScriptSerializer 设置格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5881204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 15:32:00  来源:igfitidea点击:

How to set formatting with JavaScriptSerializer when JSON serializing?

.netjsonserializationformattingjavascriptserializer

提问by Peter17

I am using JavaScriptSerializer for serializing objects to the file to the JSON format. But the result file has no readable formatting. How can I allow formating to get a readable file?

我正在使用 JavaScriptSerializer 将对象序列化为 JSON 格式的文件。但是结果文件没有可读的格式。如何允许格式化以获得可读文件?

采纳答案by Alex Zhevzhik

It seemed to be that there is no built-in tool for formatting JSON-serializer's output.
I suppose the reason why this happened is minimizing of data that we send via network.

似乎没有用于格式化 JSON 序列化器输出的内置工具。
我想发生这种情况的原因是最小化我们通过网络发送的数据。

Are you sure that you need formatted data in code? Or you want to analize JSON just during debugging?

您确定需要在代码中格式化数据吗?或者您只想在调试期间分析 JSON?

There is a lot of online services that provide such functionality: 1, 2. Or standalone application: JSON viewer.

有很多在线服务提供这样的功能:1, 2。或独立应用程序:JSON viewer

But if you need formatting inside application, you can write appropriate codeby yourself.

但是如果您需要在应用程序内部进行格式化,您可以自己编写适当的代码

回答by xelibrion

You could use JSON.NETserializer, it supports JSON formatting

您可以使用JSON.NET序列化程序,它支持 JSON 格式

string body = JsonConvert.SerializeObject(message, Formatting.Indented);

Yon can download this packagevia NuGet.

Yon 可以通过 NuGet下载这个包

回答by Mark Lakata

Here's my solution that does not require using JSON.NET and is simpler than the code linked by Alex Zhevzhik.

这是我的解决方案,不需要使用 JSON.NET,并且比 Alex Zhevzhik 链接的代码更简单。

    using System.Web.Script.Serialization; 
    // add a reference to System.Web.Extensions


    public void WriteToFile(string path)
    {
        var serializer     = new JavaScriptSerializer();
        string json        = serializer.Serialize(this);
        string json_pretty = JSON_PrettyPrinter.Process(json);
        File.WriteAllText(path, json_pretty );
    }

and here is the formatter

这是格式化程序

class JSON_PrettyPrinter
{
    public static string Process(string inputText)
    {
        bool escaped = false;
        bool inquotes = false;
        int column = 0;
        int indentation = 0;
        Stack<int> indentations = new Stack<int>();
        int TABBING = 8;
        StringBuilder sb = new StringBuilder();
        foreach (char x in inputText)
        {
            sb.Append(x);
            column++;
            if (escaped)
            {
                escaped = false;
            }
            else
            {
                if (x == '\')
                {
                    escaped = true;
                }
                else if (x == '\"')
                {
                    inquotes = !inquotes;
                }
                else if ( !inquotes)
                {
                    if (x == ',')
                    {
                        // if we see a comma, go to next line, and indent to the same depth
                        sb.Append("\r\n");
                        column = 0;
                        for (int i = 0; i < indentation; i++)
                        {
                            sb.Append(" ");
                            column++;
                        }
                    } else if (x == '[' || x== '{') {
                        // if we open a bracket or brace, indent further (push on stack)
                        indentations.Push(indentation);
                        indentation = column;
                    }
                    else if (x == ']' || x == '}')
                    {
                        // if we close a bracket or brace, undo one level of indent (pop)
                        indentation = indentations.Pop();
                    }
                    else if (x == ':')
                    {
                        // if we see a colon, add spaces until we get to the next
                        // tab stop, but without using tab characters!
                        while ((column % TABBING) != 0)
                        {
                            sb.Append(' ');
                            column++;
                        }
                    }
                }
            }
        }
        return sb.ToString();
    }

}

回答by Giles

I also wanted to be able to have formatted JSON without relying on a third-party component. Mark Lakata's solution worked well (thanks Mark), but I wanted the brackets and tabbing to be like those in Alex Zhevzhik's link. So here's a tweaked version of Mark's code that works that way, in case anyone else wants it:

我还希望能够在不依赖第三方组件的情况下格式化 JSON。Mark Lakata 的解决方案运行良好(感谢 Mark),但我希望括号和制表符与 Alex Zhevzhik 链接中的一样。所以这里有一个经过调整的 Mark 代码版本,可以这样工作,以防其他人想要它:

/// <summary>
/// Adds indentation and line breaks to output of JavaScriptSerializer
/// </summary>
public static string FormatOutput(string jsonString)
{
    var stringBuilder = new StringBuilder();

    bool escaping = false;
    bool inQuotes = false;
    int indentation = 0;

    foreach (char character in jsonString)
    {
        if (escaping)
        {
            escaping = false;
            stringBuilder.Append(character);
        }
        else
        {
            if (character == '\')
            {
                escaping = true;
                stringBuilder.Append(character);
            }
            else if (character == '\"')
            {
                inQuotes = !inQuotes;
                stringBuilder.Append(character);
            }
            else if (!inQuotes)
            {
                if (character == ',')
                {
                    stringBuilder.Append(character);
                    stringBuilder.Append("\r\n");
                    stringBuilder.Append('\t', indentation);
                }
                else if (character == '[' || character == '{')
                {
                    stringBuilder.Append(character);
                    stringBuilder.Append("\r\n");
                    stringBuilder.Append('\t', ++indentation);
                }
                else if (character == ']' || character == '}')
                {
                    stringBuilder.Append("\r\n");
                    stringBuilder.Append('\t', --indentation);
                    stringBuilder.Append(character);
                }
                else if (character == ':')
                {
                    stringBuilder.Append(character);
                    stringBuilder.Append('\t');
                }
                else if (!Char.IsWhiteSpace(character))
                {
                    stringBuilder.Append(character);
                }
            }
            else
            {
                stringBuilder.Append(character);
            }
        }
    }

    return stringBuilder.ToString();
}