Json.NET可以创建可读的Json文件吗



我正在Mono上用C#构建一个应用程序,并尝试使用Json.NET将对象序列化为Json。我遇到的问题是生成的JSON没有空白,可读性也不强。

[{"Title":"Third Post","Link":"http://example.com/third/link.html","Excerpt":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nibh velit, imperdiet id felis a, semper cursus tellus. Cras dapibus a libero at pharetra. Suspendisse nunc augue, elementum sit amet scelerisque vitae, luctus sed nulla.","Count":0},{"Title":"Second Post","Link":"http://example.com/second/link.html","Excerpt":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nibh velit, imperdiet id felis a, semper cursus tellus. Cras dapibus a libero at pharetra. Suspendisse nunc augue, elementum sit amet scelerisque vitae, luctus sed nulla.","Count":2},{"Title":"First Post","Link":"http://example.com/first/link.html","Excerpt":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nibh velit, imperdiet id felis a, semper cursus tellus. Cras dapibus a libero at pharetra. Suspendisse nunc augue, elementum sit amet scelerisque vitae, luctus sed nulla.","Count":6}]

我希望生成更像这样的东西:

[
    {
        "Title":"Third Post",
        "Link":"http://example.com/third/link.html",
        "Excerpt":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nibh velit, imperdiet id felis a, semper cursus tellus. Cras dapibus a libero at pharetra. Suspendisse nunc augue, elementum sit amet scelerisque vitae, luctus sed nulla.",
        "Count":0
    },
    {
        "Title":"Second Post",
        "Link":"http://example.com/second/link.html",
        "Excerpt":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nibh velit, imperdiet id felis a, semper cursus tellus. Cras dapibus a libero at pharetra. Suspendisse nunc augue, elementum sit amet scelerisque vitae, luctus sed nulla.",
        "Count":2
    },
    {
        "Title":"First Post",
        "Link":"http://example.com/first/link.html",
        "Excerpt":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nibh velit, imperdiet id felis a, semper cursus tellus. Cras dapibus a libero at pharetra. Suspendisse nunc augue, elementum sit amet scelerisque vitae, luctus sed nulla.",
        "Count":6
    }
]

有没有一种方法可以将这种空白自动添加到输出中?

您可以在JsonWriterFormatting属性上使用Formatting.Indented值,如下所示:

writer.Formatting = Formatting.Indented;

如果您只使用JsonSerializer,则使用SerializeObject方法的重载;其中一些采用Formatting参数,您可以将其设置为Formatting.Indented

相关内容

  • 没有找到相关文章

最新更新