3

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.

3
  • Are you sure that your object graph is small? Are you sure that it doesn't continually traverse from one lazy-loaded collection to another, gradually loading the entire database? Commented Sep 19, 2014 at 10:38
  • I am going to confirm this next week,- but briefly looking at it I saw no issue. Commented Sep 19, 2014 at 16:26
  • I just verified my object graph, it is not the object itself but the returned proxy that is the cause (See answer below). Commented Sep 24, 2014 at 16:09

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the great answer. I never looked in detail at the proxy class but that makes sense now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.