JSON Serialize IDictionary from nHibernate (Proxy Issues)

Nov 18, 2010 at 12:10 AM

Already posted once on Stack overflow, but I am in need of a solution very quickly, so I am branching out as much as possible.. ( http://stackoverflow.com/questions/4208670/serializing-idictionaryt-k-from-nhibernate-to-json )

Given this code structure, mapped with Fluent nHibernate

[JsonObject(MemberSerialization.OptIn)]
class Customer
{
 [JsonProperty]
 public virtual int Id { get; set; }
 [JsonProperty]
 public virtual Cart Cart { get; set; }
}

[JsonObject(MemberSerialization.OptIn)]
class Cart
{
 [JsonProperty]
 public virtual int Id { get; set; }
 [JsonProperty]
 public virtual IDictionary<Product,int> Products { get; set; }
}

[JsonObject(MemberSerialization.OptIn)]
class Product
{
 [JsonProperty]
 public virtual int Id { get; set; }
 [JsonProperty]
 public virtual string Name { get; set; }
}

I am trying to serialize an instance of Customer to JSON using JSON.NET. My problem is the Proxies generated for the Dictionary. I get a result like this ..

 

{
 "Id": 1,
 "Cart": {
    "Id": 1,
    "Products": {
        "Castle.Proxies.ProductProxy": 10,
        "Castle.Proxies.ProductProxy": 20
    }
 }
}

I have the following code to use for the nHibernate Proxies. (also found on stack overflow, I don't take credit for this)

    public class NHibernateContractResolver : DefaultContractResolver
    {
        protected override List<MemberInfo> GetSerializableMembers(Type objectType)
        {
            if (typeof(INHibernateProxy).IsAssignableFrom(objectType))
            {
                return base.GetSerializableMembers(objectType.BaseType);
            }
            else
            {
                return base.GetSerializableMembers(objectType);
            }
        }
    }

But I still get the same results. Please, any information you can provide is invaluable. This is really driving me nuts. I am new to both nHibernate, JSON.NET, and Castle.Windsor, trying to learn as quickly as I can to get my application up and running. 

A sample of the code I am using for serialization is as follows;
var json = JsonConvert.SerializeObject(customer, Formatting.Indented, new JsonSerializerSettings
                        {
                            NullValueHandling = NullValueHandling.Ignore,
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                            ContractResolver = new NHibernateContractResolver()
                        });
Console.WriteLine(json);