[英]Symfony 2.7 + JMS Serializer + MaxDepth
I am using the JMS Serializer bundle to serialize Symfony entities into json. 我正在使用JMS序列化程序包将Symfony实体序列化为json。 Everything is working fine until I start using the MaxDepth annotation to avoid a deep recursion.
在开始使用MaxDepth批注以避免深度递归之前,一切工作正常。
I have an entity called "Category" which has "Subcategories", if I don't make use of MaxDepth annotation when I serialize it, it works perfectly and generates a json object the way it should be with the complete tree of subcategories: 我有一个名为“ Category”的实体,该实体具有“ Subcategories”,如果我在序列化时不使用MaxDepth批注,它会很好地工作并以完整的子类别树的方式生成json对象:
{
"id": 1,
"name": "Category 1",
"subcategories": [{
"id": 3,
"name": "Category 1-1",
"subcategories": [{
"id": 7,
"name": "Category 1-1-1",
"subcategories": []
}]
}, {
"id": 4,
"name": "Category 1-2",
"subcategories": []
}]
}
I would like to have only the first level of subcategories serialized, so I have tried configuring my entity this way: 我只想序列化第一级子类别,因此我尝试通过以下方式配置我的实体:
class Category
{
....
/**
* @ORM\OneToMany(targetEntity="Category", mappedBy="parentCategory")
* @MaxDepth(1)
*/
private $subcategories;
....
}
But for some reason I don't understand when I enable the maxdepth checks, using the following code: 但是由于某些原因,我无法使用以下代码启用maxdepth检查:
$serializedObj = $jms->serialize($obj, 'json', SerializationContext::create()->enableMaxDepthChecks());
I get this weird result (no subcategory encoded but it knows that there are two): 我得到这个奇怪的结果(没有子类别编码,但它知道有两个):
{
"id": 1,
"name": "Categoria 1",
"subcategories": [{}, {}]
}
Any idea on what's going on? 有什么想法吗?
Thank you! 谢谢!
I had a similar problem and fixed is this way: 我有一个类似的问题,并且是这样解决的:
In the Student class: 在学生班:
/**
* @ORM\ManyToOne(targetEntity="school", inversedBy="student")
* @ORM\JoinColumn(name="school_id", referencedColumnName="id")
* @JMS\Serializer\Annotation\MaxDepth(2)
*/
protected $school;
In the Student controller: 在学生控制器中:
/**
* @FOS\RestBundle\Controller\Annotations\View(serializerEnableMaxDepthChecks=true)
*/
public function getStudentsAction() {
$students = $this->getDoctrine()
->getRepository('AppBundle:Student')
->findAll();
return $students;
}
Nothing of the school
gets serialized, this is exactly what I needed! school
什么都没有序列化,这正是我所需要的!
当我曾经遇到过类似的问题时,这是由于未在子实体中使用相同的序列化程序组引起的,因此它给出了一个空对象(没有序列化的属性)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.