Serialize Nhibernate object for JSON

Asked

Viewed 78 times

0

How can I serialize a Nhibernate object for JSON. When I try to serialize error by saying that it is not possible to serialize an object in context.

  • 1

    What method are you using to serialize? What is the complete error message? Put code and print to help..

2 answers

1

You should not serialize a domain object. You should always load your domain object, with Nhibernate for example, and turn it into a Viewmodel, ie a representation of that object for a given call.

If you serialize a domain object, the serializer will go through all the properties of your object, including lists, you run an enormous risk of encountering a cyclic reference error when serializing. Below an example:

public class Cliente
{
   public List<Pedido> Pedidos {get;set;}
}

public class Pedido
{
   public Cliente Cliente {get;set;
}

If you load a Customer and serialize the client object, it will also serialize the Order list and each requested object will have the Customer’s reference, which will be serialized as well. This loops in, it’s called cyclic reference.

0


I managed to serialize, I believe it should be because the mapping was with Lazy enabled, I put the Lazy loads to false and it worked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.