JMSSerializerBundle icon indicating copy to clipboard operation
JMSSerializerBundle copied to clipboard

Apply separately many JMS serialization groups on the same function

Open ahmed-bhs opened this issue 7 years ago • 3 comments

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.

ahmed-bhs avatar Mar 28 '18 19:03 ahmed-bhs

i guess so.. do not understand the question to be honest.

goetas avatar Mar 28 '18 21:03 goetas

It's very simple:

use JMS\Serializer\SerializationContext;

/**
 * @FOSRest\QueryParam(name="group")
 */
public function getArticlesAction(ParamFetcherInterface $paramFetcher)
{
    $groupName = $paramFetcher->get('group');
    $context = new SerializationContext();
    $context->setGroups([$groupName]); // you can specify more than one group

    return $this->get('jms_serializer')->toArray($data, $context);
    // or you can use serialize($data, 'json', $context)
}

zaerl avatar Mar 30 '18 12:03 zaerl

Still do not understand. Are you trying to report a bug, a feature request or something else?

goetas avatar Mar 30 '18 12:03 goetas