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

时间:2011-05-04 09:18:50

标签: .net json serialization formatting javascriptserializer

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

4 个答案:

答案 0 :(得分:33)

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

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

Yon可以通过NuGet下载this package

答案 1 :(得分:19)

这是我的解决方案,不需要使用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 );
    }

这是格式化程序

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

}

答案 2 :(得分:10)

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

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

有很多在线服务提供此类功能:12。 或独立应用程序:JSON viewer

但如果你需要在应用程序内部进行格式化,你可以自己编写appropriate code

答案 3 :(得分:8)

我还希望能够在不依赖第三方组件的情况下格式化JSON。 Mark Lakata的解决方案效果很好(感谢Mark),但我希望括号和标签与Alex Zhevzhik的链接相似。所以这里有一个马克思代码的调整版本,以这种方式工作,万一其他人想要它:

/// <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
                {
                    stringBuilder.Append(character);
                }
            }
            else
            {
                stringBuilder.Append(character);
            }
        }
    }

    return stringBuilder.ToString();
}