简体   繁体   English

C#在JSON中搜索而不反序列化

[英]C# Search in JSON without deserialization

I have a JSON text file in my Windows 10 Universal App that is rather large (>40MB). 我的Windows 10 Universal App中有一个JSON文本文件相当大(> 40MB)。 It's an array of objects like this: 这是一个像这样的对象数组:

[{"prop1": "X", "prop2": "hjk", "prop3": "abc"},
 {"prop1": "X", "prop2": "lmn", "prop3": "def"},
 {"prop1": "Y", "prop2": "opq", "prop3": "abc"},
 {"prop1": "Y", "prop2": "rst", "prop3": "def"}]

I want to be able to retrieve only a few lines, for example every object that includes the string "abc" in any property and also "Y" on prop1. 我希望能够只检索几行,例如,在任何属性中包含字符串“abc”的每个对象以及prop1上的“Y”。

Expected result: 预期结果:

[{prop1: "Y", prop2: "opq", prop3: "abc"}]

I'm afraid of deserializing it all as it might be too much for lower-end devices like phones. 我害怕将其全部反序列化,因为对于像手机这样的低端设备来说它可能太多了。 Can this be done perhaps using JSON.NET? 可以使用JSON.NET完成吗?

If you want to avoid reading the entire document into memory at once, you can use the JsonTextReader class . 如果要避免一次将整个文档读入内存,可以使用JsonTextReader It doesn't do much for you automatically, and it's forward-only. 它不会自动为你做太多,而且它只是前瞻性的。 Example usage: 用法示例:

using (var fs = File.OpenRead(path))
using (var textReader = new StreamReader(fs))
using (var reader = new JsonTextReader(textReader))
{
    while (reader.Read())
    {
        if (reader.TokenType == JsonToken.StartObject)
        {
            var obj = JObject.Load(reader);
            Debug.WriteLine("{0} - {1}", obj["id"], obj["name"]);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM