无缓冲串在内存中写入JSON到流 [英] Writing JSON to a stream without buffering the string in memory

查看:145
本文介绍了无缓冲串在内存中写入JSON到流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过建立文档了明确写JSON到。例如:

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

这将产生:

[
  {
    "foo": 1,
    "bar": 2.3
  }
]

这种方法的好处是,没有什么需要在存储器中进行缓冲。在我的情况,我写了很多的JSON流中。解决方案如这个涉及创建你在内存中的所有对象,然后将它们连载到一个大的字符串在内存中,然后最后写该字符串流和垃圾收集,大概从。我想保持我的记忆中使用低,写出元素,而从另一个文件/数据库/等读取数据流。

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.

这种方法是通过 rapidjson库可在C ++中。

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并通过其<一个确实支持该href="http://james.newtonking.com/projects/json/help/index.html?topic=html/WriteJsonWithJsonTextWriter.htm"相对=nofollow> JsonWriter 类。

JSON.NET does indeed support this via its JsonWriter class.

我的例子是这样写:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆