简体   繁体   English

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

[英]How to set formatting with JavaScriptSerializer when JSON serializing?

I am using JavaScriptSerializer for serializing objects to the file to the JSON format.我正在使用 JavaScriptSerializer 将文件中的对象序列化为 JSON 格式。 But the result file has no readable formatting.但是结果文件没有可读的格式。 How can I allow formating to get a readable file?如何允许格式化以获得可读文件?

You could use JSON.NET serializer, it supports JSON formatting您可以使用JSON.NET序列化器,它支持 JSON 格式

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

Yon can download this package via NuGet.您可以通过 NuGet 下载package。

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

}

It seemed to be that there is no built-in tool for formatting JSON-serializer's output.似乎没有用于格式化 JSON-serializer 的 output 的内置工具。
I suppose the reason why this happened is minimizing of data that we send via network.我想发生这种情况的原因是最大限度地减少了我们通过网络发送的数据。

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 .有许多提供此类功能的在线服务:1、2 Or standalone application: JSON viewer .或独立应用程序: JSON 查看器

But if you need formatting inside application, you can write appropriate code by yourself.但是如果您需要在应用程序内部进行格式化,您可以自己编写相应的代码

I also wanted to be able to have formatted JSON without relying on a third-party component.我还希望能够在不依赖第三方组件的情况下格式化 JSON。 Mark Lakata's solution worked well (thanks Mark), but I wanted the brackets and tabbing to be like those in Alex Zhevzhik's link. Mark Lakata 的解决方案运行良好(感谢 Mark),但我希望括号和制表符与 Alex Zhevzhik 链接中的一样。 So here's a tweaked version of Mark's code that works that way, in case anyone else wants it:所以这里有一个经过调整的 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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用JavaScriptSerializer将序列化为JSON的麻烦 - Trouble Serializing To JSON Using JavaScriptSerializer JSON.parse没有解析Json字符串。 使用JavaScriptSerializer进行序列化 - JSON.parse not parsing Json string. Serializing with JavaScriptSerializer 正确使用JavaScriptSerializer进行序列化 - Serializing with JavaScriptSerializer properly JSON 序列化时如何本地化? - How to localize when JSON-serializing? Dictionary中的对象是什么 <string, object> 什么时候使用JavaScriptSerializer反序列化Json? - What is the object in Dictionary<string, object> when Deserializing Json using JavaScriptSerializer? 使用 Netwonsoft 库序列化 JSON 时如何按字母顺序对属性进行排序? - How to sort properties alphabetically when serializing JSON using Netwonsoft library? 序列化为 XML 时如何处理 JSON 键中的空格? - How to handle spaces in JSON keys when serializing to XML? JavaScriptSerializer默认情况下序列化为JSON吗? - JavaScriptSerializer serializes to JSON by default? JavaScriptSerializer。 如何从JSON反序列化字符串数组? - JavaScriptSerializer. How to deserialize a string array from JSON? 使用System.Web.Script.Serialization.JavascriptSerializer反序列化JSON - 如何? - Using System.Web.Script.Serialization.JavascriptSerializer to deserialize JSON - how to?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM