Symfony2,FOSRestBundle:序列化组 return 空
Symfony2, FOSRestBundle : Serialization groups return empty
我正在使用 FOSRest Bundle 构建一个小型 API,我想在其中 return 一个资源,但只公开一些属性。
我正在使用 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
作为响应,您可以 return JsonResponse,如下所示:
$context = new SerializationContext();
$context->setGroups("myGroup");
$json = $this->get("serializer")->serialize($result, 'json', $context);
return new JsonResponse($json, 200, [], true);
我还建议您将序列化程序配置移至 YAML 文件,如所述here
使用exclusion_policy默认排除所有属性,然后为某些组添加。
AppBundle\Entity\EntityClass:
exclusion_policy: ALL
在 config.yml 文件的 JMS 序列化程序配置中,您必须指定放置所有序列化配置的目录,如下所示:
jms_serializer:
metadata:
directories:
APP:
namespace_prefix: "AppBundle"
path: "@AppBundle/Resources/config/serializer/"
我正在使用 FOSRest Bundle 构建一个小型 API,我想在其中 return 一个资源,但只公开一些属性。 我正在使用 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 作为响应,您可以 return JsonResponse,如下所示:
$context = new SerializationContext();
$context->setGroups("myGroup");
$json = $this->get("serializer")->serialize($result, 'json', $context);
return new JsonResponse($json, 200, [], true);
我还建议您将序列化程序配置移至 YAML 文件,如所述here
使用exclusion_policy默认排除所有属性,然后为某些组添加。
AppBundle\Entity\EntityClass:
exclusion_policy: ALL
在 config.yml 文件的 JMS 序列化程序配置中,您必须指定放置所有序列化配置的目录,如下所示:
jms_serializer:
metadata:
directories:
APP:
namespace_prefix: "AppBundle"
path: "@AppBundle/Resources/config/serializer/"