一次反序列化json数组流一项 [英] Deserialize json array stream one item at a time

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

问题描述

我将一个大对象数组序列化为一个 json http 响应流.现在我想一次一个地从流中反序列化这些对象.是否有任何 C# 库可以让我这样做?我看过 json.net,但似乎我必须一次反序列化完整的对象数组.

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

澄清:我想一次从流中读取一个 json 对象并将其反序列化.

解决方案

为了增量读取 JSON,您需要结合使用 JsonTextReaderStreamReader.但是,您不必从阅读器手动读取所有 JSON.您应该能够利用 Linq-To-JSON API 从读取器加载每个大对象,以便您可以更轻松地使用它.

举个简单的例子,假设我有一个看起来像这样的 JSON 文件:

<预><代码>[{"name": "foo",身份证":1},{"name": "酒吧",身份证":2},{"name": "baz",身份证":3}]

从文件中增量读取它的代码可能如下所示.(在您的情况下,您将用您的响应流替换 FileStream.)

using (FileStream fs = new FileStream(@"C:	empdata.json", FileMode.Open, FileAccess.Read))使用 (StreamReader sr = new StreamReader(fs))使用 (JsonTextReader reader = new JsonTextReader(sr)){而 (reader.Read()){if (reader.TokenType == JsonToken.StartObject){//从流中加载每个对象并用它做一些事情JObject obj = JObject.Load(reader);Console.WriteLine(obj["id"] + " - " + obj["name"]);}}}

上面的输出看起来像这样:

1 - foo2 - 酒吧3 - 巴兹

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}.....]

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

解决方案

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.

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 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:	empdata.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天全站免登陆