Reputation: 10906
I have an Entity of mine which I would like to expose in a JSON API that I'm developing, the problem is that in this particular controller, there is just one field which I don't want to expose. Is there a way to exclude it from serialization from within the controller?
I know I can annotate my entity so the serializer just passes by that field, but what happens in all the other cases? This is really the exception.
Upvotes: 1
Views: 2285
Reputation: 7808
You can assign each property to a group, then define that group in a context when serializing from the controller.
Your entity:
use JMS\Serializer\Annotations as Serializer;
class Comment
{
/** @Serializer\Groups({"main", "secondary"}) */
private $id;
/** @Serializer\Groups({"main", "secondary"}) */
private $title;
/** @Serializer\Groups({"main", "secondary"}) */
private $name;
/** @Serializer\Groups({"main"}) */
private $email;
/** @Serializer\Groups({"main", "secondary"}) */
private $message;
}
Then in your controller
use JMS\Serializer\SerializationContext;
$serializer->serialize(
new Comment(),
'json',
SerializationContext::create()->setGroups(array('secondary'))
);
In this example, the email field is excluded from the serialized data, but only for the group named secondary
. You can of course call these groups whatever you like.
Upvotes: 5