简体   繁体   中英

C# Search in JSON without deserialization

I have a JSON text file in my Windows 10 Universal App that is rather large (>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.

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?

If you want to avoid reading the entire document into memory at once, you can use the JsonTextReader class . 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"]);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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