Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newtonsoft Json - OutOfMemoryException

All,

Environment: ASP.net 2.0, Nhibernate 3.3, Json.net (latest, 6.x)

I am using latest version of Newtonsoft.Json library. When I load an entity using nhibernate (my entities reference other entities and are loaded lazily) I receive either an out of memory exception or stackoverflow exception.

Code for outofmemory exception:

JsonSerializerSettings settings = new JsonSerializerSettings();
    settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
    settings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
    string json = JsonConvert.SerializeObject(container.DataItem, settings);

Code for stackoverflow exception:

JsonSerializerSettings settings = new JsonSerializerSettings();
    settings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
    settings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
    string json = JsonConvert.SerializeObject(container.DataItem, settings);

People have these issues but there seems to be no solution. I see responses such a your graph is to large or too deep but my object graph is small,- I just call the code above lots of times (once per each object). I need a fix for this.

like image 487
ActiveX Avatar asked Jul 02 '26 02:07

ActiveX


1 Answers

you are using lazy loading so NHibernate hands back proxies here and there and these proxies have references to a System.Type object which will have endless loops and also a reference to the session and sessionfactory which will be heavy on its own, check NHibernate.Proxy.INHibernateProxy.

So either:

  • eager load the things to serialize or
  • specify directly which properties to serialize or
  • don't serialize entities alltogether
like image 141
Firo Avatar answered Jul 05 '26 02:07

Firo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!