Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

c# - Writing JSON to a stream without buffering the string in memory

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...