Cosmin
Cosmin

Reputation: 2214

Out of memory for JObject

I have a problem when I try to parse a large json file, which has around 200mb. I'm doing it with Newtonsoft.Json. It gives OutOfMemory exception.

This is my code:

using (StreamReader sr=File.OpenText("path"))
        {
            JObject file= (JObject)JToken.ReadFrom(new JsonTextReader(sr));
        }

How can I do this ? ( preferable using JObject )

Upvotes: 4

Views: 3667

Answers (1)

German Latorre
German Latorre

Reputation: 11148

You can use JsonTextReader to read text in a DataReader fashion as stated in this question:

Incremental JSON Parsing in C#

You will have to code your own logic to process JSON data, but it will for sure solve your memory issues:

using (var reader = new JsonTextReader(File.OpenText("path")))
{
    while (reader.Read())
    {
        // Your logic here (anything you need is in [reader] object), for instance:
        if (reader.TokenType == JsonToken.StartArray)
        {
            // Process array
            MyMethodToProcessArray(reader);
        }
        else if (reader.TokenType == JsonToken.StartObject)
        {
            // Process object
            MyMethodToProcessObject(reader);
        }
    }
}

You would actually build a recursive JSON parser.

Upvotes: 4

Related Questions