简体   繁体   中英

JMS Serializer Exclude Entity field in Symfony2 Controller

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM