我正在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
}
]
有没有一种方法可以将这种空白自动添加到输出中?
您可以在JsonWriter
的Formatting
属性上使用Formatting.Indented
值,如下所示:
writer.Formatting = Formatting.Indented;
如果您只使用JsonSerializer
,则使用SerializeObject
方法的重载;其中一些采用Formatting
参数,您可以将其设置为Formatting.Indented
。