【问题标题】:How to serialize data into indented json [duplicate]如何将数据序列化为缩进的json [重复]
【发布时间】:2016-05-13 00:19:50
【问题描述】:

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

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

这是我得到的结果:

[

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

[

【问题讨论】:

标签: c# json file


【解决方案1】:

将序列化程序的格式设置为缩进。

var serializer = new JsonSerializer();
serializer.Formatting = Formatting.Indented;
serializer.Serialize(file, this.users);    

【讨论】:

    【解决方案2】:

    改用这个:

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

    【讨论】:

    • 也可以直接将 IO 流写入内存然后再写入,但 Formatting.Indented 是正确的。
    • @JonathonChase 确实,您的解决方案绝对更好。此外,对 OP 的修改较少。点个赞吧~
    猜你喜欢
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    • 1970-01-01
    • 2012-08-19
    相关资源
    最近更新 更多