Doctrine2、PersistentCollection 和 JMS 序列化程序 [英] Doctrine2, PersistentCollection and JMS Serializer

查看:31
本文介绍了Doctrine2、PersistentCollection 和 JMS 序列化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有 oneToMany 关系的实体,我可以使用;

I have an Entity with a oneToMany relationship, I can get the associated items using;

$this->getQueuedItems()

这将返回 DoctrineORMPersistentCollection 对象,然后我将其传递给 JMS Serializer 像这样;

This returns DoctrineORMPersistentCollection object, I am then passing this to JMS Serializer like so;

$serializer = $container->get('serializer');
$json = $serializer->serialize($this->getQueuedItems(), 'json');

但是使用 var_dump() 输出 $json 结果;

But outputting $json using var_dump() results in;

string(2) "[]"

string(2) "[]"

这是错误的.那里有数据,因为如果我在 $this->getQueuedItems() 上执行 foreach() 我得到数据.

Which is wrong. There is data there, because if I do a foreach() over $this->getQueuedItems() I get data.

如何使用 JMS Serializer 将 DoctrineORMPersistentCollection 序列化为 JSON?

How can I use JMS Serializer to serialise DoctrineORMPersistentCollection into JSON?

谢谢

推荐答案

PersistentCollection 对象是 Iterator Aggregate 而不是数组.区别在于 Iterator 是一个可以迭代的对象,因此可能包含也可能不包含在任何时候序列化为数组所需的数据.

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.

要将集合序列化为 JSON,请尝试以下操作:

To serialize the Collection as JSON, try the following:

$serializer = $container->get('serializer');
$arr        = $this->getQueuedItems()->toArray();
$json       = $serializer->serialize($arr, 'json');

如果您对键不太感兴趣,您也可以使用 getValues,而不是 toArray.

If you're not too fussed about the keys, you could also use getValues, rather than toArray.

这篇关于Doctrine2、PersistentCollection 和 JMS 序列化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆