Writing JSON to a stream without buffering the string in memory

后端 未结 1 998
一整个雨季
一整个雨季 2020-12-17 18:51

I would like to write JSON to a Stream by building the document up explicitly. For example:

var stream = ...;
var writer = new JsonWriter(stream         


        
相关标签:
1条回答
  • 2020-12-17 18:54

    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();
    }
    
    0 讨论(0)
提交回复
热议问题