如何将数据序列化为缩进的json

Art*_*Art 5 c# json file

我正在使用此代码将用户序列化为json文本文件.

if (File.Exists(path))
{
    using (var file = File.CreateText(path))
    {
        var serializer = new JsonSerializer();
        serializer.Serialize(file, this.users);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我得到的结果:

[输出]

我怎样才能得到这样的结果:

[漂亮地打印]

Jon*_*ase 10

将序列化程序上的格式设置为"缩进".

var serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
serializer.Serialize(file, this.users);    
Run Code Online (Sandbox Code Playgroud)


Xia*_*312 9

改用这个:

if (File.Exists(path))
{
    using (var file = File.CreateText(path))
    {
        var json = JsonConvert.SerializeObject(this.users, Formatting.Indented);
        file.Write(json);
    }
}
Run Code Online (Sandbox Code Playgroud)