简体   繁体   English

序列化为JSON以每行获取一个对象

[英]Serialize to JSON to get one object per line

Is it possible to serialize object collection in a way that we get one JSON object per line? 是否可以以每行一个JSON对象的方式序列化对象集合? Like this: 像这样:

{tag1: value1, tag2: value2}, 
{tag1: value3, tag2: value6}, 
{tag1: value4, tag2: value7}, 
{tag1: value5, tag2: value8}

As I know, I can serialize to have "pretty" and indented JSON or one-line JSON, which is not what I need. 据我所知,我可以序列化为具有“漂亮”和缩进的JSON或单行JSON,这不是我所需要的。

It sounds like you want newline-delimited JSON . 听起来您想要换行符分隔的JSON It's the same as what you have in your question but without the trailing commas. 它与问题中的内容相同,但没有逗号结尾。

You can make a simple helper method to create this format using Json.Net like this: 您可以使用Json.Net创建一个简单的辅助方法来创建这种格式,如下所示:

public static string Serialize(IEnumerable items)
{
    StringBuilder sb = new StringBuilder();
    foreach (var item in items)
    {
        sb.AppendLine(JsonConvert.SerializeObject(item));
    }
    return sb.ToString();
}

Better yet, just stream the items directly to your file: 更好的是,只需将项目直接流式传输到您的文件中:

public static void SerializeToFile(IEnumerable items, string fileName, bool append = true)
{
    using (StreamWriter sw = new StreamWriter(fileName, append))
    using (JsonWriter writer = new JsonTextWriter(sw))
    {
        var ser = new JsonSerializer();
        foreach (var item in items)
        {
            ser.Serialize(writer, item);
            writer.WriteWhitespace(Environment.NewLine);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM