Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft.Json - Out of memory exception while deserializing big object

I have a problem deserializing a JSON file of about 1GB. When I run the following code I get an out of memory exception:

using (FileStream sr = new FileStream("myFile.json", FileMode.Open, FileAccess.Read))
{
  using (StreamReader reader = new StreamReader(sr))
  {
    using (JsonReader jsReader = new JsonTextReader(reader))
    {
      JsonSerializer serializer = new JsonSerializer();
      dataObject = serializer.Deserialize<T>(jsReader);
    }
  }
}

the exception is thrown by

Newtonsoft.Json.Linq.JTokenWriter.WriteValue(Int64 value)

The serialization works well, here is the code I'm using

using (StreamWriter reader = new StreamWriter("myFile.json"))
{
   using (JsonReader jsWriter = new JsonWriter(reader))
   {
      JsonTextWriter jsonWriter = new JsonTextWriter(jsWriter) { Formatting = Formatting.Indented };
      JsonSerializer ser = new JsonSerializer();
      ser.Serialize(jsonWriter, dataObject, dataObject.GetType());
      jsonWriter.Flush();
    }
}}

Am I doing something wrong in the deserialization? Can you help suggesting a way to deserialize big json object?

Thanks

like image 451
cmarlowe88 Avatar asked Nov 23 '15 10:11

cmarlowe88


People also ask

Is Newtonsoft JSON still supported?

Yet Newtonsoft. Json was basically scrapped by Microsoft with the coming of . NET Core 3.0 in favor of its newer offering designed for better performance, System. Text.

Does Jsonconvert Deserializeobject throw exception?

Serialization or deserialization errors will typically result in a JsonSerializationException .

What is the use of Jsonconvert Deserializeobject?

Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings.


1 Answers

According to Newtonsoft.Json Performance Tips your approach has to work (because you read via stream and it should make portion from your file). I can't figure out why your code doesn't work.

But you can try another approach, that was described in the next article - Parsing Big Records with Json.NET

like image 75
RredCat Avatar answered Sep 30 '22 16:09

RredCat