5

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!

Ignacio Correia
  • 3,611
  • 8
  • 39
  • 68
  • It is common to have different classes for the domain model and the data transfer objects. – Oskar Berggren Aug 25 '13 at 14:11
  • but then only for this, i will have to maintain 2 classes, i will have to duplicate 60-70 class only for DTO purpose. isn't there any nicer way? I will go DTO way only if i don't find any other nicer solution. may be writter a dummy JsonConverter is a better idea. –  Aug 26 '13 at 04:10
  • There are probably other ways to do it. Often the DTO classes don't look exactly like the domain model classes, because the latter models the concepts in the domain, while the DTOs corresponds to the use cases. Your mileage may vary. – Oskar Berggren Aug 26 '13 at 09:46

1 Answers1

4

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);
    }
}