簡體   English   中英

JMS Serializer覆蓋FOSRestBundle中的組

[英]JMS Serializer Overriding Groups in FOSRestBundle

我讀了這篇關於覆蓋子屬性組的文章

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將返回具有所有user_detailuser_profile組的用戶,但friends屬性中包含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"組進行序列化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM