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

发布于 2024-11-05 03:53:40 字数 82 浏览 6 评论 0原文

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

梦里泪两行 2024-11-12 03:53:40

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

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

您可以下载 此包 通过 NuGet。

You could use JSON.NET serializer, it supports JSON formatting

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

Yon can download this package via NuGet.

尘曦 2024-11-12 03:53:40

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

}

Here's my solution that does not require using JSON.NET and is simpler than the code linked by 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();
    }

}
眼泪也成诗 2024-11-12 03:53:40

我还希望能够在不依赖第三方组件的情况下格式化 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();
}

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:

/// <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();
}
青衫负雪 2024-11-12 03:53:40

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

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

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

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

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.

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

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

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

一花一树开 2024-11-12 03:53:40

关于

public static string FormatOutput(string jsonString):

非常感谢 - 它很有用。或者,要使用空间,它对我有用:
stringBuilder.Append('\t', ...
替换为
FormatOutput_NewLine(stringBuilder, ...

private static void FormatOutput_NewLine(StringBuilder stringBuilder, int indentation)
        {
            const string xNEWLINE = "\r\n";
            const string xIndent = "    ";

            stringBuilder.Append(xNEWLINE);
            int i = 0;
            while (i < indentation)
            {
                stringBuilder.Append(xIndent);
                i++;
            }
        }

About

public static string FormatOutput(string jsonString):

Thanks a lot - it's useful. Alternatively, to use space, it worked for me:
stringBuilder.Append('\t', ...
to replace with
FormatOutput_NewLine(stringBuilder, ...

private static void FormatOutput_NewLine(StringBuilder stringBuilder, int indentation)
        {
            const string xNEWLINE = "\r\n";
            const string xIndent = "    ";

            stringBuilder.Append(xNEWLINE);
            int i = 0;
            while (i < indentation)
            {
                stringBuilder.Append(xIndent);
                i++;
            }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文