4

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?

Thomas
  • 4,030
  • 4
  • 40
  • 79
  • I suggest you try it on a "lower-end" device. Deserialization of json is fairly light weight. – Robert McKee Dec 01 '15 at 22:01
  • http://jsonlint.com/ does like that json. those {} sets need names or something – Ňɏssa Pøngjǣrdenlarp Dec 01 '15 at 22:04
  • 3
    Sure, you can use [`JsonTextReader`](http://www.newtonsoft.com/json/help/html/ReadJsonWithJsonTextReader.htm) directly. See [Deserialize json array stream one item at a time](http://stackoverflow.com/questions/20374083) or [Issues parsing a 1GB json file using JSON.NET](http://stackoverflow.com/questions/30812828). – dbc Dec 01 '15 at 22:05
  • @Plutonix jsonlint.com is complaining because the property names aren't quoted. – Brian Rogers Dec 01 '15 at 22:08

1 Answers1

6

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"]);
        }
    }
}