Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an OutOfMemoryException while serialising to JSON?

I am serializing , a MultiDictionary<String,Object>

http://powercollections.codeplex.com/ to json .

It has 618 elements with elements being deeply nested ,i.e. a single Object may have several dictionary like objects in it . I am using JSON.Net

String json = JsonConvert.SerializeObject(json, Newtonsoft.Json.Formatting.Indented);

what am i missing ?

MORE INFO: - This was working fine till i was using dynamic , i had to switch to MultiDictionary to allow multiple properties of the same name . It works for most cases , only when the number of items is large , it breaks .

UPDATE: -

I have been able to get a hold of the Memory consumption but cutting down on some elements that were getting added recursively to each element.

like image 979
ashutosh raina Avatar asked Dec 25 '11 17:12

ashutosh raina


People also ask

What is JSON serialization exception?

JsonSerializationException(String, String, Int32, Int32, Exception) Initializes a new instance of the JsonSerializationException class with a specified error message, JSON path, line number, line position, and a reference to the inner exception that is the cause of this exception.

Can you serialize JSON?

NET objects as JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer. Serialize method. The JSON output is minified (whitespace, indentation, and new-line characters are removed) by default.


1 Answers

Assuming you don't have Circular References - if you can't store the whole thing in memory use a StreamWriter(JsonWriter or TextWriter) in Newtonsoft v4.0.30319

using (TextWriter writer = File.CreateText("LocalJSONFile.JSON"))
{
    var serializer = new JsonSerializer();
    serializer.Serialize(writer, myObject);
}

Use JsonWriter if you are trying to pass the string

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

using(JsonWriter writer = new JsonTextWriter(sw))
{
  var serializer = new JsonSerializer();
  serializer.Serialize(writer, myObject);
}
like image 81
Sam Avatar answered Oct 23 '22 10:10

Sam