Search code examples
symfonyfosrestbundlejmsserializerbundle

FOSRestBundle and JMSSerializer runtime expose


My Symfony2 API uses FOSRestBundle and JMSSerializer, with property annotations, but there are many times when I don't want to expose every property. I understand JMS has exclusion groups, but I can't figure out how to include those in my Symfony controllers. There should be a way to use PHP on a dynamic basis but that seems to be missing from the documentation too.


Solution

  • If you use View class like in this example, you can set serialization context with setSerializationContext method

    public function getUsersAction()
    {
        $data = // get data, in this case list of users.
        $view = $this->view($data, 200)
            ->setSerializationContext(SerializationContext::create()->setGroups(array('list')))
        ;
    
        return $this->handleView($view);
    }