将 JSON 写入流而不在内存中缓冲字符串 [英] Writing JSON to a stream without buffering the string in memory
问题描述
我想通过显式构建文档将 JSON 写入 Stream
.例如:
var stream = ...;var writer = new JsonWriter(stream);writer.BeginArray();{writer.BeginObject();{writer.String("foo");writer.Number(1);writer.String("bar");writer.Number(2.3);}writer.EndObject();}writer.EndArray();
这将产生:
<预><代码>[{富":1,酒吧":2.3}]这种方法的好处是不需要在内存中缓冲任何东西.在我的情况下,我正在向流中写入大量 JSON.诸如这个之类的解决方案涉及在内存中创建所有对象,然后将它们序列化为内存中的大字符串,最后写入这个字符串到流和垃圾收集,可能来自 LOH.我想保持较低的内存使用率,在从另一个文件/DB/etc 流读取数据时写出元素.
这种方法可通过 rapidjson 库在 C++ 中使用.
我已经为此搜索了很多,但没有找到解决方案.
原来我需要在 Google 上使用一段时间.
JSON.NET 确实通过其 JsonWriter 支持这一点
类.
我的例子会写成:
Stream stream = ...;使用 (var streamWriter = new StreamWriter(stream))使用 (var writer = new JsonTextWriter(streamWriter)){writer.Formatting = Formatting.Indented;writer.WriteStartArray();{writer.WriteStartObject();{writer.WritePropertyName("foo");writer.WriteValue(1);writer.WritePropertyName("bar");writer.WriteValue(2.3);}writer.WriteEndObject();}writer.WriteEndArray();}
I would like to write JSON to a Stream
by building the document up explicitly. For example:
var stream = ...;
var writer = new JsonWriter(stream);
writer.BeginArray();
{
writer.BeginObject();
{
writer.String("foo");
writer.Number(1);
writer.String("bar");
writer.Number(2.3);
}
writer.EndObject();
}
writer.EndArray();
This would produce:
[
{
"foo": 1,
"bar": 2.3
}
]
The benefit of this approach is that nothing needs to be buffered in memory. In my situation, I'm writing quite a lot of JSON to the stream. Solutions such as this one involve creating all your objects in memory, then serialising them to a large string in memory, then finally writing this string to the stream and garbage collecting, probably from the LOH. I want to keep my memory use low, writing out elements while reading data from another file/DB/etc stream.
This kind of approach is available in C++ via the rapidjson library.
I've searched around a fair bit for this and haven't found a solution.
Turns out I needed to Google for a bit longer.
JSON.NET does indeed support this via its JsonWriter
class.
My example would be written:
Stream stream = ...;
using (var streamWriter = new StreamWriter(stream))
using (var writer = new JsonTextWriter(streamWriter))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartArray();
{
writer.WriteStartObject();
{
writer.WritePropertyName("foo");
writer.WriteValue(1);
writer.WritePropertyName("bar");
writer.WriteValue(2.3);
}
writer.WriteEndObject();
}
writer.WriteEndArray();
}
这篇关于将 JSON 写入流而不在内存中缓冲字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!