小编典典

使用Json.NET序列化为NDJSON

json

是否可以使用Json.NET
序列化为NDJSON换行分隔的JSON)?Elasticsearch
API使用NDJSON进行批量操作,我找不到任何暗示 任何 .NET库都支持此格式的信息。

这个答案提供指导反序列化NDJSON,并有人指出,一个能够独立序列每一行和新行加入,但我不一定会调用
支持


阅读 554

收藏
2020-07-27

共1个答案

小编典典

由于Json.NET当前没有将集合序列化为NDJSON的内置方法,因此最简单的答案是TextWriter使用单独JsonTextWriter的一行写一行,并为每行设置[`CloseOutput

false`](http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonWriter_CloseOutput.htm):

public static partial class JsonExtensions
{
    public static void ToNewlineDelimitedJson<T>(Stream stream, IEnumerable<T> items)
    {
        // Let caller dispose the underlying stream 
        using (var textWriter = new StreamWriter(stream, new UTF8Encoding(false, true), 1024, true))
        {
            ToNewlineDelimitedJson(textWriter, items);
        }
    }

    public static void ToNewlineDelimitedJson<T>(TextWriter textWriter, IEnumerable<T> items)
    {
        var serializer = JsonSerializer.CreateDefault();

        foreach (var item in items)
        {
            // Formatting.None is the default; I set it here for clarity.
            using (var writer = new JsonTextWriter(textWriter) { Formatting = Formatting.None, CloseOutput = false })
            {
                serializer.Serialize(writer, item);
            }
            // https://web.archive.org/web/20180513150745/http://specs.okfnlabs.org/ndjson/
            // Each JSON text MUST conform to the [RFC7159] standard and MUST be written to the stream followed by the newline character \n (0x0A). 
            // The newline charater MAY be preceeded by a carriage return \r (0x0D). The JSON texts MUST NOT contain newlines or carriage returns.
            textWriter.Write("\n");
        }
    }
}

样品提琴

由于单个NDJSON行可能很短,但行数可能很大,因此此答案提出了一种流传输解决方案,以避免分配大于85kb的单个字符串的必要性。如 Newtonsoft
Json.NET Performance
Tips中所述

,此类大字符串最终会出现在大对象堆上,并可能随后降低应用程序性能。

2020-07-27