反序列化JSON数组流一个项目在一个时间 [英] Deserialize json array stream one item at a time

查看:176
本文介绍了反序列化JSON数组流一个项目在一个时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我大序列化对象的数组到JSON HTTP响应流。现在,我想在一个时间序列化从流中的一个,这些对象。是否有任何C#库,可以让我做到这一点?我看着json.net但似乎我不得不一次反序列化对象的完整阵列。

I serialize an array of large objects to a json http response stream. Now I want to deserialize these objects from the stream one at a time. Are there any c# libraries that will let me do this? I've looked at json.net but it seems I'd have to deserialize the complete array of objects at once.

[{large json object},{large json object}.....]

澄清:我想在一个时间来读取流中的一个JSON对象和反序列化

Clarification: I want to read one json object from the stream at a time and deserialize it.

推荐答案

为了逐步阅读JSON,你需要结合使用 JsonTextReader 的StreamReader 。但是,就不一定必须从阅读器手动读取所有的JSON。你应该能够利用LINQ到JSON API从读者加载每个大对象,这样你可以用它更轻松地工作。

In order to read the JSON incrementally, you'll need to use a JsonTextReader in combination with a StreamReader. But, you don't necessarily have to read all the JSON manually from the reader. You should be able to leverage the Linq-To-JSON API to load each large object from the reader so that you can work with it more easily.

对于一个简单的例子,说我有一个看起来像这样的JSON文件:

For a simple example, say I had a JSON file that looked like this:

[
  {
    "name": "foo",
    "id": 1
  },
  {
    "name": "bar",
    "id": 2
  },
  {
    "name": "baz",
    "id": 3
  }
]

code逐步从文件中读取它看起来可能像下面这样。 (在你的情况,你会替换你的响应流中的FileStream。)

Code to read it incrementally from the file might look something like the following. (In your case you would replace the FileStream with your response stream.)

using (FileStream fs = new FileStream(@"C:\temp\data.json", FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
using (JsonTextReader reader = new JsonTextReader(sr))
{
    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.StartObject)
        {
            // Load each object from the stream and do something with it
            JObject obj = JObject.Load(reader);
            Console.WriteLine(obj["id"] + " - " + obj["name"]);
        }
    }
}

上面的输出是这样的:

Output of the above would look like this:

1 - foo
2 - bar
3 - baz

这篇关于反序列化JSON数组流一个项目在一个时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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