Question

I am able to serialize proxy objects using below code:

public class NHibernateContractResolver : DefaultContractResolver
{
    protected override JsonContract CreateContract(Type objectType)
    {
        if (typeof(NHibernate.Proxy.INHibernateProxy).IsAssignableFrom(objectType))
            return base.CreateContract(objectType.BaseType);
        return base.CreateContract(objectType);
    }
}

But how can I make JSON.NET ignore the NHibernate Proxy objects during serialization.

The problem I am facing is that, the parent object is fetching 1000's of child object, where as I want to send JSON only for the parent object, so I want to ignore proxy object and fetch only eager loaded relationships.

And if I comment above code, then I get the error for JSON.NET failing to serialize the proxy objects.

Please help!

Was it helpful?

Solution

write a dummy class like this.

public class NhProxyJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        writer.WriteNull();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(INHibernateProxy).IsAssignableFrom(objectType);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top