How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application? How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application? symfony symfony

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?


With php5.4 now you can do :

use JsonSerializable;/*** @Entity(repositoryClass="App\Entity\User")* @Table(name="user")*/class MyUserEntity implements JsonSerializable{    /** @Column(length=50) */    private $name;    /** @Column(length=50) */    private $login;    public function jsonSerialize()    {        return array(            'name' => $this->name,            'login'=> $this->login,        );    }}

And then call

json_encode(MyUserEntity);


Another option is to use the JMSSerializerBundle. In your controller you then do

$serializer = $this->container->get('serializer');$reports = $serializer->serialize($doctrineobject, 'json');return new Response($reports); // should be $reports as $doctrineobject is not serialized

You can configure how the serialization is done by using annotations in the entity class. See the documentation in the link above. For example, here's how you would exclude linked entities:

 /*** Iddp\RorBundle\Entity\Report** @ORM\Table()* @ORM\Entity(repositoryClass="Iddp\RorBundle\Entity\ReportRepository")* @ExclusionPolicy("None")*/..../*** @ORM\ManyToOne(targetEntity="Client", inversedBy="reports")* @ORM\JoinColumn(name="client_id", referencedColumnName="id")* @Exclude*/protected $client;


You can automatically encode into Json, your complex entity with:

use Symfony\Component\Serializer\Serializer;use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;use Symfony\Component\Serializer\Encoder\JsonEncoder;$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));$json = $serializer->serialize($entity, 'json');