Newtonsoft Json - OutOfMemoryException
All,
Environment: ASP.net 2.0, Nhibernate 3.3, Json.net (latest, 6.x)
I am using the latest version of the Newtonsoft.Json library. When I load an object using nhibernate (my entities are referencing other objects and loading lazily) I get an out of memory exception or a stackoverflow exception.
Outofmemory exception code:
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 problems, but there seems to be no solution. I see responses such that your graph is large or too deep, but my object graph is small - I just call the code above many times (one for each object). I need to fix this.
you are using lazy loading, so NHibernate passes proxies here and there, and those proxies have object references System.Type
that will have infinite loops, and a session and sessionfactory reference that will be heavy on their own, check NHibernate.Proxy.INHibernateProxy
.
So either:
- load things to serialize, or
- specify which properties are serialized or
- do not serialize entities alltogether