是否可以使用NDJSON (新行分隔的JSON)序列化到Json.NET?Elasticsearch使用NDJSON进行批量操作,我找不到任何.NET库都支持这种格式。
这个答案为反序列化NDJSON提供了指导,并且注意到可以单独序列化每一行并使用换行符连接,但我不一定会称之为支持。
发布于 2017-06-27 19:19:01
由于Json.NET目前没有将集合序列化为NDJSON的内置方法,最简单的答案是为每一行使用单独的JsonTextWriter写入单个TextWriter,为每个行设置CloseOutput = false:
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行可能很短,但行数可能很大,这个答案提出了一个流解决方案,以避免分配大于85 be的单个字符串的必要性。正如在http://www.newtonsoft.com/json/help/html/Performance.htm#MemoryUsage中解释的那样,这样大的字符串最终出现在大对象堆上,随后可能会降低应用程序的性能。
发布于 2017-06-27 19:05:31
你可以试试这个:
string ndJson = JsonConvert.SerializeObject(value, Formatting.Indented);但是现在我看到,您不只是希望序列化的对象被很好地打印出来。如果您正在序列化的对象是某种集合或枚举,那么您不能仅通过序列化每个元素来做到这一点吗?
StringBuilder sb = new StringBuilder();
foreach (var element in collection)
{
sb.AppendLine(JsonConvert.SerializeObject(element, Formatting.None));
}
// use the NDJSON output
Console.WriteLine(sb.ToString());https://stackoverflow.com/questions/44787652
复制相似问题