2017-08-07 64 views
0

我正在使用FOSRest Bundle來構建一個小API,其中我想返回一個資源但只公開一些屬性。 我正在使用Symfony的默認串行器。Symfony2,FOSRestBundle:序列化組返回空

這裏是我的實體:

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()部分,我得到了整個實體,包括我不想要的屬性。

我在做什麼錯? 感謝

+0

你構建的API?如果它是這樣的話,我會建議你這樣做: $ context = new SerializationContext(); $ context-> setGroups(「myGroup」); ($ result,'json',$ context);} $ json = $ this-> get(「serializer」) - > serialize($ result,'json',$ context); 返回新的JsonResponse($ json,200,[],true); – Vladislav

回答

0

首先所有的控制器應延長FOSRestController 正如你可以返回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 

在JMS串行配置在config.yml文件,你必須指定你把全部關閉連載配置目錄,如:

jms_serializer: 
    metadata: 
     directories: 
      APP: 
       namespace_prefix: "AppBundle" 
       path: "@AppBundle/Resources/config/serializer/" 
+0

感謝您的回答。我的控制器確實擴展了'FOSRestController',但我沒有使用jms_serializer出於不同的原因。此外,我想堅持fosrest返回語法(例如:'$ view = $ this-> view($ myEntity,200) - > setTemplate(「default/myEntity.html.twig」) - > setTemplateVar('myEntity ');') – AdrienXL