创建不带数组缩进的JSON [英] Creating JSON without array indentation
问题描述
我通常会得到非常大的JSON,其中包含很多列表以及列表中的许多元素.我的目标是得到左边的结构,而不是右边的结构. 正确的结构是我从Newtonsoft得到的. 是否有另一个库可以让我像这样打印它?
I usually get very big JSON with a lot of lists and a lot of elements inside the lists. My goal is to get the left structure instead of the right one. The right structure is what I get from Newtonsoft. Is there another library that gives me the control to print it like this?
最佳情况是:
推荐答案
如果您将JsonTextWriter
类子类化并重写WriteIndent
方法,则可以使用Json.Net(又名Newtonsoft Json)获得所需的缩进:
You can get the indenting you want with Json.Net (a.k.a. Newtonsoft Json) if you subclass the JsonTextWriter
class and override the WriteIndent
method like this:
public class CustomJsonTextWriter : JsonTextWriter
{
public CustomJsonTextWriter(TextWriter writer) : base(writer)
{
}
protected override void WriteIndent()
{
if (WriteState != WriteState.Array)
base.WriteIndent();
else
WriteIndentSpace();
}
}
然后创建一个小的辅助方法,以使其易于使用自定义编写器:
Then create a small helper method to make it easy to use the custom writer:
public static class JsonHelper
{
public static string SerializeWithCustomIndenting(object obj)
{
using (StringWriter sw = new StringWriter())
using (JsonWriter jw = new CustomJsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jw, obj);
return sw.ToString();
}
}
}
这是一个有效的演示: https://dotnetfiddle.net/RusBGI
Here is a working demo: https://dotnetfiddle.net/RusBGI
这篇关于创建不带数组缩进的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!