Json.net ignores nhibernate proxy objects during serialization

I can serialize proxy objects using the code below:

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 NHibernate Proxy objects during serialization.

The problem I am facing is that the parent object is retrieving 1000 child objects, where, since I want to send JSON only for the parent object, so I want to ignore the proxy object and only get the relations loaded.

And if I comment on the code above, then I get an error for JSON.NET that cannot serialize proxy objects.

Please, help!

+4
source share
1 answer

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); } } 
+4
source

Source: https://habr.com/ru/post/1498734/


All Articles