Pie*_*erc 3 php rest serialization symfony fosrestbundle
Symfony 3.1.7 + FOSRestBundle 最新版本
<?php
namespace PM\ApiBundle\Controller;
...
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\View\View;
class ArticlesController extends FOSRestController
{
/**
* @ApiDoc(
* section="articles",
* resource=true,
* description="Get articles published"
* )
* @Rest\View(serializerGroups={"article"})
* @Rest\Get("/articles")
*/
public function getArticlesAction(Request $request)
{
$articles = $this->getDoctrine()
->getManager()
->getRepository('PMPlatformBundle:Article')
->findAllDateDesc();
/* @var $articles Article[] */
return $articles;
}
Run Code Online (Sandbox Code Playgroud)
然后在我的文章实体中,我使用正确的使用语句添加了这个注释 @Groups({"article"})。
我得到的默认序列化程序:
[
[],
[]
]
Run Code Online (Sandbox Code Playgroud)
我得到了 Whit JMS 序列化程序(捆绑):
{
"0": {},
"1": {}
}
Run Code Online (Sandbox Code Playgroud)
(我在 db 中有两篇文章)似乎无法识别“文章”组。当我使用没有这个注释的默认序列化程序时,我得到一个循环错误。
怎么了 ?
[编辑] 与相同的行为
/**
* @ApiDoc(
* section="articles",
* resource=true,
* description="Get articles published"
* )
* @Rest\View()
* @Rest\Get("/articles")
*/
public function getArticlesAction(Request $request)
{
$context = new Context();
$context->addGroup('article');
$articles = $this->getDoctrine()
->getManager()
->getRepository('PMPlatformBundle:Article')
->findAllDateDesc();
/* @var $articles Article[] */
$view = $this->view($articles, 200);
$view->setContext($context);
return $view;
}
Run Code Online (Sandbox Code Playgroud)
响应仍然是空的。
您可以保留 symfony 的默认序列化程序。不需要 JMSSerializer。
您可能忘记在 config.yml 中激活序列化程序的注释(https://symfony.com/doc/current/serializer.html#using-serialization-groups-annotations)
#app/config/config.yml
framework:
....
serializer: { enable_annotations: true }
Run Code Online (Sandbox Code Playgroud)
有必要在 config.yml ( http://symfony.com/doc/master/bundles/FOSRestBundle/3-listener-support.html , http://symfony.com/doc/master/bundles/ FOSRestBundle/view_response_listener.html )
#app/config/config.yml
fos_rest:
view:
view_response_listener: 'force'
Run Code Online (Sandbox Code Playgroud)
那应该有效!
| 归档时间: |
|
| 查看次数: |
2526 次 |
| 最近记录: |