Csharp/C#教程:使用Json.NET序列化为NDJSON分享


使用Json.NET序列化为NDJSON

是否可以使用Json.NET序列化为NDJSON ( Newline Delimited JSON)? Elasticsearch API使用NDJSON进行批量操作,我发现没有任何迹象表明任何 .NET库都支持这种格式。

这个答案提供了反序列化NDJSON的指导,并且注意到可以独立地序列化每一行并加入换行符,但我不一定称之为支持

最简单的答案是使用单独的JsonTextWriter为每一行写入单个TextWriter为每个行设置CloseOutput = false

 public static partial class JsonExtensions { public static void ToNewlineDelimitedJson(Stream stream, IEnumerable 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(TextWriter textWriter, IEnumerable 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://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性能提示中所解释的那样,这样的大字符串最终会出现在大对象堆上,并可能随后降低应用程序性能。

你可以试试这个:

 string ndJson = JsonConvert.SerializeObject(value, Formatting.Indented); 

但是现在我看到你不仅仅想要将序列化对象打印出来。 如果您要序列化的对象是某种集合或枚举,您是否可以通过序列化每个元素来自己执行此操作?

上述就是C#学习教程:使用Json.NET序列化为NDJSON分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 StringBuilder sb = new StringBuilder(); foreach (var element in collection) { sb.AppendLine(JsonConvert.SerializeObject(element, Formatting.None)); } // use the NDJSON output Console.WriteLine(sb.ToString()); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1025407.html

(0)
上一篇 2022年1月8日
下一篇 2022年1月8日

精彩推荐