-->

Problems try encode entity to json

2019-08-25 04:01发布

问题:

im try encode an Doctrine entity as JSON string, to send as Ajax response. So, i check the doc: The Serializer Component

I try with this code:

$em = $this->getDoctrine()->getManager();
// Get the entities repository
$sesiones_registradas = $em->getRepository('AuditBundle:AuditSession')->findAll();

// Instance the object
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));

// Convert only an item
foreach($sesiones_registradas as $sesion){
    echo $serializer->normalize($sesion,'json');
    break;
}
// Stop script
die();

Last code, fails saying:

Could not normalize object of type AppsManantiales\AuditBundle\Entity\AuditSession, no supporting normalizer found.

And if change $serializer->normalize($sesion,'json') by $serializer->serialize($sesion, 'json'); The error message is:

Serialization for the format json is not supported

Any ideas ?.

回答1:

Use the JMS Serializer Bundle

The docs can be found here: http://jmsyst.com/bundles/JMSSerializerBundle



回答2:

Your problem come from the fact you inverted both normalizers and encoders.

The line:
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));
must be:
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array(new JsonEncoder()));