我正在使用FOSRest Bundle来构建一个小API,我想在其中返回一个资源,但只公开一些属性。 我正在使用Symfony的默认序列化程序。
这是我的实体:
class myEntity
{
private foo;
* @Groups({"myGroup"})
private bar;
getFoo(){...}
getBar{...}
}
和我的控制器:
* @ParamConverter("myEntity ")
public function getAction(myEntity $myEntity)
{
$context = new Context();
$context->addGroups('myGroup');
$view = $this->view($myEntity, 200)->setTemplate("default/myEntity.html.twig")->setTemplateVar('myEntity');
$view->setContext($context);
return $this->handleView($view);
}
当我尝试执行我的控制器时,我得到一个空对象作为响应:{}
如果我删除setContext()
部分,我会得到我的整个实体,包括我不想要的属性。
我做错了什么? 谢谢
首先,您的控制器应该扩展 FOSRestController 作为响应,您可以返回 JsonResponse,如下所示:
$context = new SerializationContext();
$context->setGroups("myGroup");
$json = $this->get("serializer")->serialize($result, 'json', $context);
return new JsonResponse($json, 200, [], true);
我还建议你将序列化程序配置移动到 YAML 文件,如此处所述
默认情况下,使用 exclusion_policy 排除所有属性,然后为某些组添加。
AppBundleEntityEntityClass:
exclusion_policy: ALL
在 config.yml 文件的 JMS 序列化程序配置中,您必须指定将所有序列化配置放在其中的目录,如下所示:
jms_serializer:
metadata:
directories:
APP:
namespace_prefix: "AppBundle"
path: "@AppBundle/Resources/config/serializer/"