问题
I have an Entity with a oneToMany relationship, I can get the associated items using;
$this->getQueuedItems()
This returns Doctrine\ORM\PersistentCollection object, I am then passing this to JMS Serializer like so;
$serializer = $container->get('serializer');
$json = $serializer->serialize($this->getQueuedItems(), 'json');
But outputting $json
using var_dump()
results in;
string(2) "[]"
Which is wrong. There is data there, because if I do a foreach()
over $this->getQueuedItems()
I get data.
How can I use JMS Serializer to serialise Doctrine\ORM\PersistentCollection into JSON?
Thanks
回答1:
The PersistentCollection object is an Iterator Aggregate and not an array. The distinction is that an Iterator is an object that can be iterated over and so may or may not contain the data required for serializing to an array at any one time.
To serialize the Collection as JSON, try the following:
$serializer = $container->get('serializer');
$arr = $this->getQueuedItems()->toArray();
$json = $serializer->serialize($arr, 'json');
If you're not too fussed about the keys, you could also use getValues
, rather than toArray
.
来源:https://stackoverflow.com/questions/15257769/doctrine2-persistentcollection-and-jms-serializer