I'm still having continuous difficulties getting Json.Net and NHibernate to play nicely together. Namely, in getting Json.NET to serialize a proxied NHibernate object.
I've followed the recommendations here, both for the accepted answer and the ammendments, but no dice.
The biggest problem with the above solution is that it seems that modern versions of NHibernate are using the INHibernateProxyProxy
interface to create proxies (rather than INHibernateProxy? Can anyne else confirm this?), whose base class in my case is NHibernate.Proxy.DynamicProxy.ProxyDummy
, which reveals nothing about the underlying object when I attempt to create the Json constract using my custom scontract resolver, ie:
protected override JsonContract CreateContract(Type objectType)
{
if (typeof(NHibernate.Proxy.INHibernateProxy).IsAssignableFrom(objectType))
return base.CreateContract(objectType.BaseType);
else
return base.CreateContract(objectType);
}
Does anyone have any advice for how to deal with INHibernateProxyProxy
effectively?
From forever ago but I think the problem here was actually that the proxy was not initialized before trying to serialize it.
You have to call
NHibernateUtil.Initialize(aPersistentObject.LazyProperty);
to initialize a proxy object.Afterward, the
BaseType
probably would have been correct... i.e. notProxyDummy
but the actual type needed.For me, the solution is something like this:
So when I have a REST service endpoint with a proxied type, it looks like kind of like this:
and the serializer defined in
WebService.Helper
is used to serialize the result.Note that if the serialization process happens outside of your method (as it does for me) you will always need to call to initialize the object before you actually serialize it. You may be able to do this with
Global.asax
events, but I just handle it directly in my service methods.The full Solution:
In Global.asax.cs :
And the custom contract:
Don't forget to replace : "Your.Domain.Namespace"
My problem was that not all sublists are resolved by Newtonsoft.JSON.
I added a contract resolver
At serialization add the custom contract resolver
This solves my problem.
Found it. The original type is available via
.GetInterfaces()
, ie: