php - 组注释不起作用

标签 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;
    }

然后我在我的 Article 实体中添加了这个注释 @Groups({"article"}) 和正确的使用声明。

我得到的默认序列化程序:

[
    [],
    []
]

我得到了 Whit JMS 序列化程序( bundle ):

{
    "0": {},
    "1": {}
}

(我在 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;
} 

响应仍然是空的。

最佳答案

您可以保留 symfony 的默认序列化程序。不需要 JMSSerializer。

你可能忘记在 config.yml (https://symfony.com/doc/current/serializer.html#using-serialization-groups-annotations) 中激活序列化器的注解

#app/config/config.yml
framework:
    ....
    serializer: { enable_annotations: true }

需要在config.yml中强制view_response_listener ( 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'

应该可以!

关于php - 组注释不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40999006/

相关文章:

php - 使用 AES_ENCRYPT 时 Mysqli 准备语句出现问题

php - Laravel Eloquent 不将模型保存到数据库

php - 当我知道 CNAME 存在时,为什么 dns_get_record 不显示它们?

c# - Rest call WebException 401 Unauthorized only in mixed authentication webapp

java - 如何使用 Jersey for java 在浏览器中呈现新的 .jsp 文件?

.net - 我可以在没有 .NET 库的情况下使用 Windows 身份验证使用 WCF REST 服务吗?

c++ - 如何将迭代器(或类似的东西)存储到硬盘上?

php - 在 Drupal 7 中向现有内容类型添加新字段

c# - 处理来自子 AppDomain 的不可序列化的未处理异常

java - 为什么 Jackson 实现 Serializable?