Serialize nhibernate entity to json error: Cannot serialize a Session while connected

ryudice picture ryudice · May 2, 2011 · Viewed 8.1k times · Source

I'm trying to serialize an nhibernate entity in to json but I always get this error saying Cannot serialize a Session while connected? Does it has something to do with nhibernate proxy?

Answer

Zar Shardan picture Zar Shardan · Aug 22, 2012

I started getting the same error when I switched from System.Web.Script.Serialization.JavaScriptSerializer to Newtonsoft.Json.

Using the contract resolver from this answer fixed this problem:

string output = JsonConvert.SerializeObject(theObject,
                new JsonSerializerSettings()
                {
                    ContractResolver = new NHibernateContractResolver()
                });