Json中的默认标识符。网络似乎是2个空格:
var result = JsonConvert.SerializeObject(jsonString, Formatting.Indented);
为了清晰起见,我想将其更改为4个空格,但我似乎找不到应用该属性的正确方法。它似乎是存在的,因为我发现了一些类似的代码(直接链接在这里):
using (JsonTextWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
jw.IndentChar = ' ';
jw.Indentation = 4;
jw.WriteRaw(config.ToString());
}
…不过,如果可能的话,我希望在这种情况下避免不必要地处理流。
任何建议吗?
我将创建一个实用程序类,用正确的缩进序列化它,类似于JsonConvert.SerializeObject
的做法:
public static class JsonConvertEx
{
public static string SerializeObject<T>(T value)
{
StringBuilder sb = new StringBuilder(256);
StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);
var jsonSerializer = JsonSerializer.CreateDefault();
using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.IndentChar = ' ';
jsonWriter.Indentation = 4;
jsonSerializer.Serialize(jsonWriter, value, typeof(T));
}
return sw.ToString();
}
}
并像这样消费:
class Program
{
static void Main(string[] args)
{
var anon = new { Name = "Yuval", Age = 1 };
var result = JsonConvertEx.SerializeObject(anon);
}
}