问题
I'm using Symfony2 and JMSSerializerBundle to build an API. The system that JMSSerializer provides to set different ways of serializing objects using groups is quite useful, however, I'm missing a way to specify which group do you want to serialize in every parameter. Example:
I have an article that is related to a user (author). Articles as well as users can be serialized as "list" or as "details", however, I want the users to be serialized as "list" always that they are retrieved from the article (because "details" group is reserved to be used to fetch the user and just the user). The problem is that if I set the serializer as "details", then the author is also serialized as "details".
In my mind, the code should be something like:
/**
* @var SCA\APIBundle\Entity\User
* @Groups({"list" => "list", "details" => "list"})
*/
private $author;
where the key of the array indicates the way the parent should be serialized, and the value indicates the way the child should be serialized.
Any clue how can I achieve this?
回答1:
It should not be done on the composed object but on the composition.
In your case, I suppose you have something like that:
class Article
{
/**
* @var User
* @Groups({"list", "details"})
*/
private $author;
}
class User
{
private $firstName;
private $lastName;
}
So if you want to expose the firstName property when serializing the composed object, you need to define the same group in the User object.
It becomes:
class Article
{
/**
* @var User
* @Groups({"list", "details"})
*/
private $author;
}
class User
{
/*
* @Groups({"list"})
*/
private $firstName;
private $lastName;
}
If you need more control, you may define more explicit groups, like "article-list", "user-firstname", "user-list-minimal", etc.
It is up to you to decide the best strategy to adopt.
来源:https://stackoverflow.com/questions/13665369/jmsserializerbundle-specify-group-per-attribute