JMSSerializerBundle
JMSSerializerBundle copied to clipboard
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.
i guess so.. do not understand the question to be honest.
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)
}
Still do not understand. Are you trying to report a bug, a feature request or something else?