如何更改实体的序列化输出?
How do I change the output of the serialization from my entity?
$normalizer = new ObjectNormalizer();
// $normalizer->setCircularReferenceLimit(2);
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
$normalizer->setIgnoredAttributes(array('users', '__initializer__', '__cloner__', 'authkey', '__isInitialized__', "products"));
$serializer = new Serializer(array($normalizer), array(new JsonEncoder()));
return new JsonResponse($serializer->serialize($product, 'json'));
这就是结果:
{
"id": 128,
"name": "product",
"price": 12,
"category": {
"id": 58,
"name": "category",
"company": {
"id": 1,
"name": "foo",
"tables": []
}
},
"description": "this is a product",
"company": {
"id": 1,
"name": "foo",
"tables": []
}
}
但是我怎样才能得到以下结果:
{
"id": 128,
"name": "product",
"price": 12,
"category": {
"name": "category"
},
"description": "this is a product",
"company": {
"id": 1,
"name": "foo",
"tables": []
}
}
如何改变这些值?
例如我想在这里:
"category": {
"name": "category" },
稍后还有 id。
看看序列化器组件Attributes Groups。我相信这就是您要找的。
您可以select每个特定响应中应包含哪些实体属性。
只需简单地在实体中设置组
/**
* @Groups({"group1", "group2"})
*/
public $foo;
然后指定组或组数组进行序列化
$serializer = new Serializer(array($normalizer));
$data = $serializer->normalize($obj, null, array('groups' => 'group1'));
有时仅组是不够的,这时您可以使用 Doctrine hydrator。这是一个有点复杂的解决方案,但这为您提供了更多的可能性。
通常,当您需要制作一个简单的 selection 时,您会使用 Attributes Groups
- 检索一个特定的实体或具有一些已连接实体的实体集合(也可以使用组进行连接)。 Doctrine hydrator
在需要聚合 selection 时使用,例如从 table 中检索没有指定关系的数据,或者将组合数据与常规数据一起添加。
$normalizer = new ObjectNormalizer();
// $normalizer->setCircularReferenceLimit(2);
$normalizer->setCircularReferenceHandler(function ($object) {
return $object->getId();
});
$normalizer->setIgnoredAttributes(array('users', '__initializer__', '__cloner__', 'authkey', '__isInitialized__', "products"));
$serializer = new Serializer(array($normalizer), array(new JsonEncoder()));
return new JsonResponse($serializer->serialize($product, 'json'));
这就是结果:
{
"id": 128,
"name": "product",
"price": 12,
"category": {
"id": 58,
"name": "category",
"company": {
"id": 1,
"name": "foo",
"tables": []
}
},
"description": "this is a product",
"company": {
"id": 1,
"name": "foo",
"tables": []
}
}
但是我怎样才能得到以下结果:
{
"id": 128,
"name": "product",
"price": 12,
"category": {
"name": "category"
},
"description": "this is a product",
"company": {
"id": 1,
"name": "foo",
"tables": []
}
}
如何改变这些值?
例如我想在这里:
"category": { "name": "category" },
稍后还有 id。
看看序列化器组件Attributes Groups。我相信这就是您要找的。
您可以select每个特定响应中应包含哪些实体属性。
只需简单地在实体中设置组
/**
* @Groups({"group1", "group2"})
*/
public $foo;
然后指定组或组数组进行序列化
$serializer = new Serializer(array($normalizer));
$data = $serializer->normalize($obj, null, array('groups' => 'group1'));
有时仅组是不够的,这时您可以使用 Doctrine hydrator。这是一个有点复杂的解决方案,但这为您提供了更多的可能性。
通常,当您需要制作一个简单的 selection 时,您会使用 Attributes Groups
- 检索一个特定的实体或具有一些已连接实体的实体集合(也可以使用组进行连接)。 Doctrine hydrator
在需要聚合 selection 时使用,例如从 table 中检索没有指定关系的数据,或者将组合数据与常规数据一起添加。