我正在尝试对 doctrine 对象进行 json 编码,而不是序列化其集合属性中的每个项目;
我想返回一个 id 数组,例如:
{"children":[200,201],"id":1}
而不是:
{"children":[{"parents":[],"id":200},{"parents":[],"id":201}],"id":1}
我正在使用jmsserializerbundle
来序列化教义对象我尝试创建一个虚拟属性并循环访问集合属性中的每个项目,这有效但感觉很脏......
控制器:
$serializer = $this->container->get('serializer');
$reports = $serializer->serialize($parent, 'json');
实体:
/**
* Parent
*
* @ORM'Table()
* @ORM'Entity
*/
class Parent
{
[...]
/**
* @ORM'ManyToMany(targetEntity="Children", inversedBy="parents")
* @Exclude
*/
private $children;
/**
* @VirtualProperty
* @SerializedName("children")
*/
public function getChildrenId()
{
$children= array();
foreach ($this->children $child){
$children[] = $child->getId();
}
return $children;
}
[...]
可以使用
@Accessor
批注来指定序列化属性时要使用的方法,这是一种更简洁的方法。
/**
* Parent
*
* @ORM'Table()
* @ORM'Entity
*/
class Parent
{
[...]
/**
* @ORM'ManyToMany(targetEntity="Children", inversedBy="parents")
* @Accessor(getter="getChildrenId")
*/
private $children;
public function getChildrenId()
{
$children = array();
foreach ($this->children as $child){
$children[] = $child->getId();
}
return $children;
}
[...]
然后,如果需要反序列化数据,还可以轻松实现资源库。
/**
* @ORM'ManyToMany(targetEntity="Children", inversedBy="parents")
* @Accessor(getter="getChildrenId", setter="setChildrenId")
*/
private $children;
public function setChildrenId($ids)
{
...
}