0

I want to serialize some objects into Json. Sometimes (not always, and I don't know what triggers it) one of these objects is a proxy, which causes the serializer to throw a circular reference error even though there is no circular reference: "A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'."

My code uses NHibernate and JavaScriptSerializer:

public static string Convert(object xiObject)
{
  var lSerialiser = new JavaScriptSerializer();

  return lSerialiser.Serialize(xiObject);
}

Lazy Loading is supposedly off, as in:

  HasManyToMany(x => x.Managers)
    .Not.LazyLoad();

It sounds really similar to this guy's problem: http://markmail.org/message/x5a2k7j7qtjmj73g#query:+page:1+mid:4r5lcggmfrcq5tby+state:results

So my plan is to use Json.net instead of JavaScriptSerializer, and implement the solution on that page, but it looks really complicated. Any other suggestions would be great.

JYX
  • 2,653
  • 2
  • 17
  • 15

2 Answers2

0

Probably you can "unproxy" object before serializing it. This article shows how to do it - Identifying NHibernate proxy classes

Community
  • 1
  • 1
Nikolay
  • 3,658
  • 1
  • 24
  • 25
  • Thanks - this link did it: http://sessionfactory.blogspot.co.uk/2010/08/hacking-lazy-loaded-inheritance.html – JYX Mar 19 '12 at 11:35
0

IMHO, the correct answer is "you don't".
Your entities (which may contain the proxies) belong in your business domain. You should be serializing DTOs, which contain only what your client needs, and no more.
Ayende writes about it in detail.

P.S. It is also considered best practice not to set the lazy-load parameter in your mappings, but instead decide whether to lazy-load or not based on the specific query you're executing. Again, Ayende explains.

J. Ed
  • 6,692
  • 4
  • 39
  • 55