Reputation: 445
I'm using JMS serializer in my Symfony projuect and i have a question about it. I want ot expose property from entity for only one specific method (one route), in other cases i dont want this property to be exposed. I would be appreciate for any advices)
Upvotes: 0
Views: 2251
Reputation: 2595
You can probably achieve this using the @Groups
annotation on your properties and then tell the serializer which groups to serialize in your controller.
use JMS\Serializer\Annotation\Groups;
class BlogPost
{
/** @Groups({"list", "details"}) */
private $id;
/** @Groups({"list", "details"}) */
private $title;
/** @Groups({"list"}) */
private $nbComments;
/** @Groups({"details"}) */
private $comments;
private $createdAt;
}
And then:
use JMS\Serializer\SerializationContext;
$serializer->serialize(new BlogPost(), 'json', SerializationContext::create()->setGroups(array('list')));
//will output $id, $title and $nbComments.
$serializer->serialize(new BlogPost(), 'json', SerializationContext::create()->setGroups(array('Default', 'list')));
//will output $id, $title, $nbComments and $createdAt.
More info here.
Upvotes: 2