Search code examples
symfonyserializationjmsserializerbundlejms-serializer

Apply separately many JMS serialization groups on the same function


I'm looking for a feature with jms_serliazer.
Ok let me explain, suppose we have a function getArticlesAction(), and a query param called group that gonna represent the group serialization name.

So, after getting the name of serialization group $paramFetcher->get ('group'), Is it possible to apply serliazer group, eather group1 or group2, based on that query param already recuperated ?

This is my example:

/**
 * @FOSRest\QueryParam(name="group")
 */
public function getArticlesAction(ParamFetcherInterface $paramFetcher)
{
    $groupName = $paramFetcher->get('group');

    //yourlogic
}

This is a part of my configuration under Entity.Article.yml, it's responsible for how the serliazation gonna be.

ArticleBundle\Entity\Article:
    properties:
        id:
            expose: true
            groups: [group1, group2]
        name:
            expose: true
            serialized_name: name
            groups: [group1]
        label:
            expose: true
            serialized_name: label
            groups: [group2]

Here in my example, if we apply the group1, we gonna get a collections of objects with (id, name) keys, and if we apply the group2, then we gonna get a collections of objects with (id, label) keys.


Solution

  • If you have the group come in via the parameter, assuming validation that it was a a valid group name, you could do this:

    In the use section of the class, add:

    use JMS\Serializer\SerializationContext;
    use Symfony\Component\HttpFoundation\Response;
    

    Then the method would be:

    /**
    * @FOSRest\QueryParam(name="group")
    */
    public function getArticlesAction(ParamFetcherInterface $paramFetcher)
    {
        $groupName = $paramFetcher->get('group');
    
        //snip - get the repo here
        $article = $articleRepo->find($articleId);
        $response = $this->get('serializer')->serialize($article, 'json', SerializationContext::create()->setGroups([$groupName]));
    
        return new Response($response, 200, ['Content-Type' => 'application/json']);
    }