Getting an OutOfMemoryException while serialising to JSON?

前端 未结 3 1721
青春惊慌失措
青春惊慌失措 2020-12-11 15:43

I am serializing , a MultiDictionary

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

It has 618 elements with elements bein

相关标签:
3条回答
  • 2020-12-11 16:23

    It appears that you're running into Ciruclar Reference that is causing OutOfMemoryException or your objects are simply too large for your memory. Use NDepend to check this.

    You might find useful getting the total size of your objects.

    0 讨论(0)
  • 2020-12-11 16:31

    It's hard to tell without knowing the exact structure of the objects being serialized, but it's possible that, since the object graph is so big, there might be circular references somewhere (an object which points to an object which in turn points to the first object), creating an infinite loop of serialization.

    EDIT :

    You may use a tool, like NDepend, to find out where the circular references are. Give the trial version a try.

    0 讨论(0)
  • 2020-12-11 16:34

    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);
    }
    
    0 讨论(0)
提交回复
热议问题