JMS 序列化程序覆盖 FOSRestBundle 中的组

JMS Serializer Overriding Groups in FOSRestBundle

我阅读了 this article 关于覆盖子属性组的内容:

use JMS\Serializer\SerializationContext;

$context = SerializationContext::create()->setGroups(array(
    'Default', // Serialize John's name
    'manager_group', // Serialize John's manager
    'friends_group', // Serialize John's friends

    'manager' => array( // Override the groups for the manager of John
        'Default', // Serialize John manager's name
        'friends_group', // Serialize John manager's friends. If you do not override the groups for the friends, it will default to Default.
    ),

    'friends' => array( // Override the groups for the friends of John
        'manager_group' // Serialize John friends' managers.

        'manager' => array( // Override the groups for the John friends' manager
            'Default', // This would be the default if you did not override the groups of the manager property.
        ),
    ),
));
$serializer->serialize($john, 'json', $context);

在 FOSRestBundle 中,我使用 @View 注释和 serializerGroups 属性:

/**
 * @Rest\Get("/api/users/{id}", name="api_get_user")
 * @Rest\View(serializerGroups={"Default", "detail", "friends":{"Default"})
 */
public function getAction(Request $request, User $user = null)
{
    return $user;
}

如何使用该注释覆盖子属性?

如果有人找到更好更短的方式带注释我可以奖励赏金(因为我无法取回)。

覆盖嵌套属性组的唯一方法是从视图中获取 序列化程序上下文 并从那里设置组。这是:

/**
 * @Rest\Get("/api/users/profile", name="api_get_profile")
 */
public function profileAction(Request $request)
{
    $user = $this->getUser();

    // sets different groups for nested properties
    $view = $this->view($user);
    $view->getContext()->setGroups(array(
        'Default',
        'user_detail',
        'user_profile',
        'friends' => array(
            'Default',
        )
    ));

    return $this->handleView($view);
}

这样我的 profileAction 将 return 一个拥有所有 user_detailuser_profile 组的用户,但是 friends [=30] 中的项目=],其中包含一个 User 数组,将只包含 Default 组中定义的属性。

这是结果:

{
    "id": 532,
    "username": "someuser",
    "email": "someuser@example.com",
    "enabled": true,
    "last_login": "2017-11-10T09:45:51+01:00",
    "notification_id": "ABC",
    "avatar_id": 3,
    "friends": [
        {
            "id": 530,
            "username": "anotheruser",
            "avatar_id": 5
        },
        {
            "id": 554,
            "username": "johndoe",
            "avatar_id": 7
        }
    ]
}

我们将 Symfony 3.4 与 FOSRestBundle 2.3.1 一起使用,并且嵌套的属性在注释中为我们工作:

class FooController extends FOSRestController
{
    /**
     * @Route("/{id}")
     * @Method({"GET"})
     * @View(serializerGroups={"Default", "api:foo:details", "subfoos"={"Default", "api:foo:summary"}})
     */
    public function fooAction(Foo $foo){
        return $foo;
    }
}

$foo->subfoos 字段用组 "Default", "api:foo:summary".

序列化