多年来,我一直在 SF2 和 SF3 上使用组注释。 我正在尝试 SF4.1。当我将 GET 发送到我的端点时,我得到一个空的 JSON。
我的 composer.json 中有趣的部分:
"friendsofsymfony/rest-bundle": "^2.3",
"jms/serializer-bundle": "^2.3",
"sensio/framework-extra-bundle": "^5.1",
"symfony/serializer-pack": "^1.0"
配置:
framework:
serializer:
enabled: true
enable_annotations: true
sensio_framework_extra:
view: { annotations: true }
fos_rest:
routing_loader:
default_format: json
view:
view_response_listener: 'force'
format_listener:
rules:
- { path: ^/, prefer_extension: true, fallback_format: json, priorities: [ json,xml, html ] }
实体
use JMS\Serializer\Annotation\Groups;
class User implements UserInterface, \Serializable
{
private $id;
/**
* @Groups({"api"})
*/
private $username;
和端点 API Controller :
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
class UserController extends FOSRestController {
public function getUserAction(Request $request, EntityManagerInterface $em)
{
$user = $em->getReference('App:User', 1);
$view = View::create();
$context = new Context();
$context->setGroups(['api']);
$view->setContext($context);
$view->setData($user);
return $this->handleView($view);
}
}
如果我删除 `$context->setGroups(['api']),JSON 将具有所有用户属性。
有什么想法吗?谢谢!
调试信息:
bin/console debug:container jms
选择以下服务之一以显示其信息[fos_rest.serializer.jms]: [0] fos_rest.serializer.jms
0
服务“fos_rest.serializer.jms”的信息 =================================================
期权值(value)
服务ID fos_rest.serializer.jms
类 FOS\RestBundle\Serializer\JMSSerializerAdapter
标签-
公开号
合成号
懒惰是
共享是
摘要号
Autowiring 没有
自动配置没有
最佳答案
默认情况下,如果安装了 JMSSerializer,FOSRest 会优先使用它。所以首先检查是否定义了 JMSSerializerBundle
定义的服务:
./bin/console debug:container jms_serializer.serializer
如果此命令显示错误消息 (ServiceNotFound),则表示未正确安装 bundle 。检查 config/bundles.php
并添加以下行(如果缺少):
JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true],
如果它确实被安装了,你可以检查fos_rest
配置,如果它可能改变序列化服务。您可以这样配置它:
fos_rest:
service:
serializer: "fos_rest.serializer.jms"
关于symfony - JMS 序列化器注释组不使用 Symfony 4 在实体上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51219057/