GiuServ GiuServ - 8 days ago 6
JSON Question

Doctrine 2: Return related objects as array

I have a User entity, that has a many to many relation with a Tipo entity.

I have the method to retrieve the related entities already working, so assuming

$u
is my user,
$u->getIdtipo()
returns all the wanted related objects.

Now, the result of the function above is a collection, but i need an array, since i want to return it as a json to my call.

I tryed to apply the
->toArray()
as well to the result of
getIdtipo()
, but the result of that operation is that it creates an array of Tipo objects, while i need an array of array.

Is possible to convert the collection of object returned by
getIdtipo
to a json, or an array of array?

Note: i would like to use the
getIdtipo()
instead of making a custom query to retrieve the same results.




answer

As from marked answer, i implemented a serializer, and used it.

From symfony documentation, i run
composer require symfony/serializer


Than I created in my main controller a function that serialize, that's what i did:

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

public function serialize($data, $format){
$encoders = array(new XmlEncoder(), new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);

return $serializer->serialize($data, $format);

}


and then simply return the user's tipo doing

$this->serialize($u->getIdtipo(), 'json'));

Answer

The easy way would be to implement JsonSerializable on Tipo like:

class Tipo implements \JsonSerializable
{
    // ...

    public function jsonSerialize() {
        return [
            'some key' => $this->someValue, // ...
        ];
    }
}

this, paired with the ArrayCollection::toArray should be enough.


Other than that you can use some sort of serializer, e.g.: