Softwire Blog

JavaScriptSerializer circular reference error when serializing a proxy object

19 April 2012, by

One day, my code suddenly started throwing circular reference errors while trying to serialize objects into JSON. There was no circular reference, and I couldn’t figure out why the couple of extra lines that I last added would affect serialization. What’s more, it only threw an error when I was logged in as certain users, and not as others.

The problem was that the object it was trying to serialize sometimes appeared as a proxy instead of the actual object. This happens if NHibernate doesn’t have enough information to resolve all the dependent objects after the first load – in our case it was dependent on the length of the chain in a parent-child tree. We first attempted to tweak our lazy loading config via .LazyLoad(Laziness.NoProxy) in our Fluent NHibernate mapping, but that laziness mode is only supported on some relationship types and not on the ManyToMany that was the cause of our problem, so this didn’t help us.

There seem to be a lot of people out there asking the same question, and some very complicated solutions being offered (such as this one using Json.Net).

However, in some cases there is a fairly easy workaround you can employ: unproxy the object before you serialize (see here).

Put this in the EntityBase:

public virtual T As<T>() where T : EntityBase
  return this as T;

And then when you want to serialize it, do something like

var lSerialiser = new JavaScriptSerializer();
unproxiedObject = originalObject.As<User>();
return lSerialiser.Serialize(unproxiedObject);

Note that this will not fix the issue in all cases. But if it works for you, then we’re glad to have been of service!