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

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

问题描述

我有一个具有oneToMany关系的实体,我可以使用以下方式获取关联的项目:

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

$this->getQueuedItems()

这将返回 Doctrine\ORM\PersistentCollection 对象,然后将其传递给 JMS序列化器,就像这样;

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');

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

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序列化器将 Doctrine\ORM\PersistentCollection 序列化为JSON?

How can I use JMS Serializer to serialise Doctrine\ORM\PersistentCollection 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.

To将集合序列化为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天全站免登陆